std::map 中的元素是否保证有序?

发布于 2024-09-11 21:11:35 字数 35 浏览 3 评论 0原文

这只是一个实现副作用(红黑树)还是c++标准保证了顺序?

Is this just an implementation side effect (red-black tree) or the order is guaranteed by the c++ standard?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

許願樹丅啲祈禱 2024-09-18 21:11:35

有序迭代不是实现细节;它由 C++ 标准保证。它是所有关联容器的基本属性 (C++03 §23.1.2/9):

关联容器的迭代器的基本属性是它们以键的非降序顺序迭代容器,其中非降序是由用于构造它们的比较定义的。对于任意两个可解引用迭代器 ij,使得从 ij 的距离为正,

 value_comp(*j, *i) == false

value_comp 是构造映射所用的比较器(默认情况下,它是 std::less)。

Ordered iteration is not an implementation detail; it is guaranteed by the C++ standard. It is a fundamental property of all associative containers (C++03 §23.1.2/9):

The fundamental property of iterators of associative containers is that they iterate through the containers in the non-descending order of keys where non-descending is defined by the comparison that was used to construct them. For any two dereferenceable iterators i and j such that distance from i to j is positive,

    value_comp(*j, *i) == false

value_comp is the comparator with which the map was constructed (by default, it is std::less<T>).

水中月 2024-09-18 21:11:35

§23.1.2/2:

每个关联容器是
Key 和排序上参数化
关系Compare会产生严格的
元素的弱排序(25.3)
密钥。 …Compare 类型的对象是
称为 a 的比较对象
容器。本次比较对象
可能是指向函数的指针或
具有适当类型的对象
函数调用运算符。

默认的Compare对象是小于函数std::less

顺序是函数的一个属性。这是一个要求,而不是副作用。

对对象进行排序是一个副作用。 23.1.2/10 和 23.1.2/9(James 引用)保证在从 begin的序列中,map/set 和 multimap/multiset 分别具有递增/非递减键>结束

§23.1.2/2:

Each associative container is
parameterized on Key and an ordering
relation Compare that induces a strict
weak ordering (25.3) on elements of
Key. … The object of type Compare is
called the comparison object of a
container. This comparison object
may be a pointer to function or an
object of a type with an appropriate
function call operator.

The default Compare object is the less-than function std::less<Key>.

The ordering is a property of the function. It's a requirement, not a side effect.

Sorting the objects is a side effect. 23.1.2/10 and 23.1.2/9 (quoted by James) guarantee that map/set and multimap/multiset have increasing/non-decreasing keys, respectively, over the sequence from begin to end.

生寂 2024-09-18 21:11:35

它由 C++ 标准保证。

It's guaranteed by the c++ standard.

忆梦 2024-09-18 21:11:35

有保证。如果您想要不受此限制的东西,请尝试 boost::unordered_map<>

Guaranteed. If you want something that's not constrained by this try boost::unordered_map<>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文