嵌套vector是如何sort的
时间: 2024-03-23 15:38:25 浏览: 15
嵌套的vector可以使用sort函数进行排序。排序时,可以通过传递自定义比较函数来指定排序的方式。比较函数需要接受两个参数,表示需要比较的两个元素。
例如,对于一个嵌套的vector<vector<int>>,可以如下排序:
```cpp
#include <vector>
#include <algorithm>
bool cmp(const std::vector<int>& a, const std::vector<int>& b) {
// 以第一个元素为关键字排序
return a[0] < b[0];
}
int main() {
std::vector<std::vector<int>> nested_vec = {{3, 2, 1}, {6, 5, 4}, {9, 8, 7}};
std::sort(nested_vec.begin(), nested_vec.end(), cmp);
// 输出排序后的结果
for (const auto& vec : nested_vec) {
for (const auto& num : vec) {
std::cout << num << " ";
}
std::cout << std::endl;
}
return 0;
}
```
上述代码以第一个元素作为关键字进行排序,输出结果为:
```
3 2 1
6 5 4
9 8 7
```
注意,排序时需要保证每个vector的大小相同,否则可能会导致运行时错误。