如果映射键/值不改变,std::map 迭代器输出顺序将保持不变?

发布于 2024-10-09 10:10:46 字数 234 浏览 0 评论 0原文

如果我不更改该映射中的键/值,是否可以保证 map::iterator 的输出顺序?

例如,我使用一些键/值初始化映射,然后执行一系列循环,并在每个循环中迭代映射并执行只读操作,每次迭代的输出是否相等?

for(i=0;i<5;i++)
 for(it=map.begin(); it!=map.end(); it++)
  // read some value from map

is the output order of a map::iterator guaranteed if I don't change the keys/values in that map?

E.g., I initialize a map with some keys/values then do a sequence of loops and in each loop iterate over the map and perform read-only actions, will the output of each iteration be equal?

for(i=0;i<5;i++)
 for(it=map.begin(); it!=map.end(); it++)
  // read some value from map

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

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

发布评论

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

评论(3

素手挽清风 2024-10-16 10:10:46

std::map 是一个有序集合。从 begin() 迭代到 end() 将始终按顺序返回映射条目。

顺序由映射的比较运算符决定,默认为 std::less

一句话:是的。

std::map is an ordered collection. Iterating from begin() to end() will always return map entries in order.

The order is determined by the comparison operator of the map which is std::less<Key> by default.

In a word: yes.

执笔绘流年 2024-10-16 10:10:46

仅在修改操作(插入、擦除、清除)时修改顺序,其他操作不会影响顺序

the order is only modified on modify operations (insert, erase, clear), other operations will not impact the ordering

小猫一只 2024-10-16 10:10:46

std::map 保证排序。如果内容不改变,地图排序也不应该改变。

我只能想到一种可能不会发生这种情况的场景:映射键是指针,比较函子取消引用键指向的对象以对它们执行比较操作。键未更改,但 do 指向的值(出于任何其他原因)。即使在那里,我也不确定标准是否强制执行 std::map 来仅在插入元素时评估比较。

std::map guarantees to be sorted. If contents don't change, map sorting shouldn't.

I can only think of a scenario in which this may not happen: map keys are pointers and comparison functor dereferences objects pointed by keys to perform comparison operations on them. Keys are not changed but values pointed by do (for any other reason). And even there I'm not sure if the standard forces implementation of std::map to evaluate comparison only at the time of inserting elements.

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