如何对vector <vector <int >>进行排序?

Mer*_*Ovn -3 c++ sorting vector

我有一个矢量:

vector<vector<int>> myvector;
Run Code Online (Sandbox Code Playgroud)

如何按顺序对字符串的字母顺序对此向量进行排序?

例如输出:

未排序:

5 9 4 12 4

7 9 3 4 7 9

6 5 11

5 8 7 3

5 9 5 1 1

排序方式:

7 9 3 4 7 9

6 5 11

5 9 5 1 1

5 9 4 12 4

5 8 7 3

jua*_*nza 6

只需使用该std::sort算法.唯一的细微之处在于它按降序排序,因此您需要更改排序标准.有两种方法可以解决这个问题.

使用自定义比较仿函数,例如std::greater:

std::sort(v.begin(), v.end(), std::greater<std::vector<int>>());  
Run Code Online (Sandbox Code Playgroud)

使用反向迭代器:

std::sort(myvector.rbegin(), myvector.rend());
Run Code Online (Sandbox Code Playgroud)

前一个版本使意图更清晰,而后一个版本可能需要一些头部刮擦和文档阅读.但两者的结果是一样的.

这是一个有效的例子:

#include <vector>
#include <algorithm>   // for std::sort
#include <functional>  // for std::greater
#include <iostream>

int main()
{    
  // Set up an example vector
  std::vector<std::vector<int>> v{{5, 9, 4, 12, 4},
                                  {7, 9, 3, 4, 7, 9},
                                  {6, 5, 11},
                                  {5, 8, 7, 3},
                                  {5, 9, 5, 1, 1}};

  // Perform the sort
  std::sort(v.begin(), v.end(), std::greater<std::vector<int>>());

  // Output the results
  for (const auto& i : v)
  {
    for (auto j : i)
      std::cout << j << " ";
    std::cout << "\n";
  }
}
Run Code Online (Sandbox Code Playgroud)

输出:

7 9 3 4 7 9
6 5 11
5 9 5 1 1
5 9 4 12 4
5 8 7 3
Run Code Online (Sandbox Code Playgroud)

  • @Lundin:我不确定你的困惑是什么.[`std :: vector :: operator <`](http://en.cppreference.com/w/cpp/container/vector/operator_cmp)由库提供.当然元素必须是LessThanComparable. (3认同)
  • @Lundin他们猜测你的类会有一个合适的`operator <`,否则你不会在你的类的向量上调用`operator <`.我真的不知道你在这里要做什么.你声称`std :: vector <int>`没有`operator <`,这完全是胡说八道. (2认同)