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
只需使用该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)