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

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

什么是2D向量?
2D向量是向量的向量。它是在向量的帮助下实现的矩阵。

// C++ code to demonstrate 2D vector
#include
#include // for 2D vector
using namespace std;
  
int main()
{
    // Initializing 2D vector "vect" with
    // values
    vector< vector > vect{{1, 2, 3},
                              {4, 5, 6},
                              {7, 8, 9}};
  
    // Displaying the 2D vector
    for (int i=0; i

输出:

1 2 3
4 5 6
7 8 9

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

// C++ code to demonstrate sorting of a
// row of 2D vector
#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:
1 3 5 
4 8 6 
7 2 9 

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

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

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

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

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

// C++ code to demonstrate sorting of a
// 2D vector on basis of a column
#include
#include // for 2D vector
#include // for sort()
using namespace std;
  
// Driver function to sort the 2D vector
// on basis of a particular column
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:
7 2 9 
3 5 1 
4 8 6 

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

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