gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:46:58 25 4
gpt4 key购买 nike

我有这个包含 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com