您可以在没有任何自定义比较器的情况下对矢量的矢量进行排序。
如果你不提供,那么
std::vector::operator<
将被使用。
此运算符对内部元素执行字典式比较。
例如:
#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
std::vector<std::vector<int>> vecs{{7, 2}, {1, 8, 5}, {3}};
// until C++20
std::sort(vecs.begin(), vecs.end());
// since C++20
std::ranges::sort(vecs);
for (const auto &v : vecs) {
for (int x : v) {
std::cout << x << ' ';
}
std::cout << '\n';
}
}
输出
1 8 5
3
7 2
注:
operator<
将首先比较第一个元素,如果两个向量中的元素相同,则将比较其余元素。
如果你
只有
想要比较第一个元素以节省性能,您仍然需要一个自定义比较器,可以按如下方式进行:
// since C++11, could also be written as a lambda expression
struct first_element_compare {
/* static since C++23*/
constexpr bool operator()(const std::vector<int>& a,
const std::vector<int>& b) const
{
// FIXME: this code crashes when a or b is empty
// we must decide how these vectors compare to each other
return a.front() < b.front();
}
};
// ...
// until C++20
std::sort(vecs.begin(), vecs.end(), first_element_compare{});
// since C++20
std::ranges::sort(vecs, first_element_compare{});