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

📅  最后修改于: 2021-05-26 03:23:52             🧑  作者: Mango

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

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

本文讨论了更多案例

就像在这组文章中提到的那样,一个2D向量也可以具有具有不同列数的行。此属性与2D数组不同,在2D数组中,所有行的列数均相同。

// C++ code to demonstrate 2D Vector
// with different no. of columns
#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}};
  
    // Displaying the 2D vector
    for (int i=0; i

输出:

1 2
3 4 5
6

情况5:根据No.排序2D向量。行中的列按升序排列。

在这种类型的排序中,2D向量根据“否”进行排序。列按升序排列。这是通过在“ sort()”中传递第三个参数作为对用户定义的显式函数的调用来实现的。

// C++ code to demonstrate sorting of
// 2D vector on basis of no. of columns
// in ascending order
#include
#include // for 2D vector
#include // for sort()
using namespace std;
  
// Driver function to sort the 2D vector
// on basis of a no. of columns in 
// ascending order
bool sizecom(const vector& v1, const vector& v2)
{
    return v1.size() < v2.size();
}
  
int main()
{
    // Initializing 2D vector "vect" with
    // values
    vector< vector > vect{{1, 2},
                               {3, 4, 5},
                               {6}};
  
    // Displaying the 2D vector before sorting
    cout << "The Matrix before sorting is:\n";
    for (int i=0; i

输出:

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

情况6:根据No.排序2D向量。行中的列以降序排列。

在这种类型的排序中,2D向量根据“否”进行排序。列按降序排列。这是通过在“ sort()”中传递第三个参数作为对用户定义的显式函数的调用来实现的。

// C++ code to demonstrate sorting of
// 2D vector on basis of no. of columns
// 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 no. of columns in 
// descending order
bool sizecom(const vector& v1, const vector& v2)
{
    return v1.size() > v2.size();
}
  
int main()
{
    // Initializing 2D vector "vect" with
    // values
    vector< vector > vect{{1, 2},
                      {3, 4, 5},
                  {6}};
  
    // Displaying the 2D vector before sorting
    cout << "The Matrix before sorting is:\n";
    for (int i=0; i

输出:

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