c++ - [C++][std::sort] 它如何在 2D 容器上工作?

标签 c++ sorting stdvector

我有这个包含 ints vector 的 vector 对象

std::vector<std::vector<int>> vec;

我一直在努力弄清楚 std::sort(vec.begin(), vec.end()) 是如何工作的。以下是我的观察:

  1. 二维 vector 按大小排序。
  2. 如果一些内部 vector 具有相同的大小,则第一个元素值较小的 vector 将具有较小的索引值。

我现在一直在生成一些二维 vector ,似乎这两个总是正确的。但是,我怀疑我的第二个假设。 std::sort 真的是这样工作的,还是只是运气让我的假设正确?

最佳答案

对 vector 元素进行排序的方式与对任何其他类型进行排序的方式相同。 std::sort使用给定的比较对象作为参数。如果没有明确传递,std::less是默认值。

std::less使用 operator< .根据 vector 文档,它:

Compares the contents of lhs and rhs lexicographically. The comparison is performed by a function equivalent to std::lexicographical_compare.


Lexicographical comparison is a operation with the following properties:

  • Two ranges are compared element by element.
  • The first mismatching element defines which range is lexicographically less or greater than the other.
  • If one range is a prefix of another, the shorter range is lexicographically less than the other.
  • If two ranges have equivalent elements and are of the same length, then the ranges are lexicographically equal.
  • An empty range is lexicographically less than any non-empty range.
  • Two empty ranges are lexicographically equal.

简而言之,词典排序与用于字典的排序相同(忽略某些语言的奇怪之处)。


2D vectors are sorted by size.

不完全是。 {1}, {3, 4}, {1, 2, 5}将被排序为 {1}, {1, 2, 5}, {3, 4} .

关于c++ - [C++][std::sort] 它如何在 2D 容器上工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55142345/

相关文章:

c++ - copy() 将除最后一个元素之外的所有元素从 vector 复制到数组 C++

c++ - boost::asio::strand post 方法性能

mysql - CakePHP 排序顺序不影响所有记录

java - Collections.sort(list) 不适用于(链接的)哈希集背后的原因?

c++ - 如何将整数 vector 插入 std::map 的键、值

c++ - 删除 std::vector<std::string> 中与另一个给定 std::string 中的字符匹配的元素

c++ - 数据类型与 arduino 和 coder.ceval 不匹配

c++ - 如何在 C++ 中模拟堆栈帧?

objective-c - iPhone Obj C——对字典的可变数组进行排序——显示一个字符串但按值排序

c++ - 为什么为const std::vector定义了operator [],而没有为const std::map定义了operator []?