C++中的向量排序

wmomyfyw  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(185)

我们可以对向量的向量进行排序,比如:

  1. {[7, 2], [1, 8], [3, 4]}

使用std::sort(vec.begin(), vec.end()),根据每个向量中的第一个元素以升序排列,还是我们需要传递自定义比较器函数给std::sort

7hiiyaii

7hiiyaii1#

您可以对向量的向量进行排序,而无需任何自定义比较器。如果您不提供,则将使用std::vector::operator<。这个操作符执行内部元素的字典序比较。
例如:

  1. #include <vector>
  2. #include <iostream>
  3. #include <algorithm>
  4. int main()
  5. {
  6. std::vector<std::vector<int>> vecs{{7, 2}, {1, 8, 5}, {3}};
  7. // until C++20
  8. std::sort(vecs.begin(), vecs.end());
  9. // since C++20
  10. std::ranges::sort(vecs);
  11. for (const auto &v : vecs) {
  12. for (int x : v) {
  13. std::cout << x << ' ';
  14. }
  15. std::cout << '\n';
  16. }
  17. }

输出

注意:operator<将首先比较第一个元素,如果它在两个向量中相同,它将比较其余的元素。如果你只想比较第一个元素来保存性能,你仍然需要一个自定义的比较器,你可以这样做:

  1. // since C++11, could also be written as a lambda expression
  2. struct first_element_compare {
  3. /* static since C++23*/
  4. constexpr bool operator()(const std::vector<int>& a,
  5. const std::vector<int>& b) const
  6. {
  7. // FIXME: this code crashes when a or b is empty
  8. // we must decide how these vectors compare to each other
  9. return a.front() < b.front();
  10. }
  11. };
  12. // ...
  13. // until C++20
  14. std::sort(vecs.begin(), vecs.end(), first_element_compare{});
  15. // since C++20
  16. std::ranges::sort(vecs, first_element_compare{});
展开查看全部

相关问题