📌  相关文章
📜  在C++中对2D向量进行排序|设置2(按行和列的降序排列)

📅  最后修改于: 2021-05-30 10:59:25             🧑  作者: Mango

我们已经讨论了在下面的集合1中对2D向量进行排序的一些情况。

在C++中对2D向量进行排序|设置1(按行和列)

本文讨论了更多案例

情况3:按降序对2D向量的特定行进行排序
这种类型的排序以降序排列2D向量的选定行。这是通过使用“ sort()”并传递一维向量的迭代器作为其参数来实现的。

// C++ code to demonstrate sorting of a
// row of 2D vector in descending order
#include
#include // for 2D vector
#include // for sort()
using namespace std;
   
int main()
{
    // Initializing 2D vector "vect" with
    // values
    vector< vector > vect{{3, 5, 1},
                               {4, 8, 6},
                               {7, 2, 9}};
    // Number of rows;
    int m = vect.size();
   
    // Number of columns (Assuming all rows
    // are of same size).  We can have different
    // sizes though (like Java).
    int n = vect[0].size();
   
    // Displaying the 2D vector before sorting
    cout << "The Matrix before sorting 1st row is:\n";
    for (int i=0; i

输出:

The Matrix before sorting 1st row is:
3 5 1 
4 8 6 
7 2 9 
The Matrix after sorting 1st row is:
5 3 1 
4 8 6 
7 2 9 

情况4:根据特定列以降序对整个2D向量进行排序。
在这种类型的排序中,将根据所选列以降序对2D向量进行完全排序。例如,如果选定的列为第二列,则第二列中具有最大值的行将成为第一行,第二列中具有第二最大值的行将成为第二行,依此类推。

{3,5,1},
{4,8,6},
{7,2,9};

在第二列对矩阵进行排序之后,我们得到

{4,8,6} //第二列中具有最大值的行
{3,5,1} //第二列中第二个最大值的行
{7,2,9}

这是通过在“ sort()”中传递第三个参数作为对用户定义的显式函数的调用来实现的。

// C++ code to demonstrate sorting of a
// 2D vector on basis of a column in
// descending order
#include
#include // for 2D vector
#include // for sort()
using namespace std;
   
// Driver function to sort the 2D vector
// on basis of a particular column in 
// descending order
bool sortcol( const vector& v1,
               const vector& v2 ) {
    return v1[1] > v2[1];
}
   
int main()
{
    // Initializing 2D vector "vect" with
    // values
    vector< vector > vect{{3, 5, 1},
                                {4, 8, 6},
                                {7, 2, 9}};
   
    // Number of rows;
    int m = vect.size();
   
    // Number of columns (Assuming all rows
    // are of same size).  We can have different
    // sizes though (like Java).
    int n = vect[0].size();
       
    // Displaying the 2D vector before sorting
    cout << "The Matrix before sorting is:\n";
    for (int i=0; i

输出:

The Matrix before sorting is:
3 5 1 
4 8 6 
7 2 9 
The Matrix after sorting is:
4 8 6 
3 5 1 
7 2 9 

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”