如果映射键/值不改变,std::map 迭代器输出顺序将保持不变?
如果我不更改该映射中的键/值,是否可以保证 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
std::map
是一个有序集合。从begin()
迭代到end()
将始终按顺序返回映射条目。顺序由映射的比较运算符决定,默认为
std::less
。一句话:是的。
std::map
is an ordered collection. Iterating frombegin()
toend()
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.
仅在修改操作(插入、擦除、清除)时修改顺序,其他操作不会影响顺序
the order is only modified on modify operations (insert, erase, clear), other operations will not impact the ordering
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.