我们可以对向量的向量进行排序,比如:
{[7, 2], [1, 8], [3, 4]}
使用std::sort(vec.begin(), vec.end()),根据每个向量中的第一个元素以升序排列,还是我们需要传递自定义比较器函数给std::sort?
std::sort(vec.begin(), vec.end())
std::sort
7hiiyaii1#
您可以对向量的向量进行排序,而无需任何自定义比较器。如果您不提供,则将使用std::vector::operator<。这个操作符执行内部元素的字典序比较。例如:
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'; }}
#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';
注意:operator<将首先比较第一个元素,如果它在两个向量中相同,它将比较其余的元素。如果你只想比较第一个元素来保存性能,你仍然需要一个自定义的比较器,你可以这样做:
operator<
// since C++11, could also be written as a lambda expressionstruct 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++20std::sort(vecs.begin(), vecs.end(), first_element_compare{});// since C++20std::ranges::sort(vecs, first_element_compare{});
// 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();
};
// ...
std::sort(vecs.begin(), vecs.end(), first_element_compare{});
std::ranges::sort(vecs, first_element_compare{});
1条答案
按热度按时间7hiiyaii1#
您可以对向量的向量进行排序,而无需任何自定义比较器。如果您不提供,则将使用
std::vector::operator<
。这个操作符执行内部元素的字典序比较。例如:
输出
注意:
operator<
将首先比较第一个元素,如果它在两个向量中相同,它将比较其余的元素。如果你只想比较第一个元素来保存性能,你仍然需要一个自定义的比较器,你可以这样做: