我有这个包含 int
s vector 的 vector 对象
std::vector<std::vector<int>> vec;
我一直在努力弄清楚 std::sort(vec.begin(), vec.end())
是如何工作的。以下是我的观察:
- 二维 vector 按大小排序。
- 如果一些内部 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/