无法增加价值限制的地图/设置迭代器
我正在尝试在地图中的索引j之后增加节点的键,但是我在将迭代器递增到下一个节点时会遇到一些错误,这是我的代码:
typedef map<int, string> My_map;
My_map my_map;
my_map[0] = "la base";
my_map[1] = "le premier";
int j = 1;
My_map::reverse_iterator first_it(my_map.rbegin());
first_it++;
My_map::reverse_iterator last_it(make_reverse_iterator(next(my_map.begin(), j - 1)));
for (My_map::reverse_iterator it = first_it ; it != last_it ; it++) {
auto handle = my_map.extract(it.base());
handle.key()++;
my_map.insert(move(handle));
}
我知道地图不能具有重复的键,所以我开始从最后一个到j-th。但是 it ++
不起作用。这与我使用 first_it ++;
时有所不同吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在它提到了副作用:
如您所见,所有迭代器都可以找到除了您关心的迭代器外。因为
it
是提取元素的迭代器,所以它现在无效。随后的尝试使用它(使用it ++
推进循环迭代)会导致不确定的行为。您可以做的是使用
std :: map :: insert
:In the documentation for
std::map::extract
it mentions the side-effects:As you can see, all the iterators are find except for the ones you care about. Because
it
is an iterator to the extracted element, it is now invalid. Subsequent attempts to use it (withit++
to advance the loop iteration) leads to undefined behavior.What you can do is use the iterator returned by
std::map::insert
:正如 @paddy 所指出的,在调用
之后。 extract()
方法并再次执行.insert()
你的所有迭代器都无效,因此你不能进一步运行修改循环。我建议使用以下有效且更快的解决方案。复制到单独的 std::vector 中,复制从
j< 开始的所有元素/code>-第一个位置。在地图中删除它们。按照您喜欢的方式在向量中修改它们,例如向所有键添加
+1
。通过地图的.insert(begin, end)
方法一次性将它们全部插入回来。复制元素的清晰向量。所有建议均在以下代码片段中实现:
在线尝试!
输出:
As pointed by @paddy, after calling
.extract()
method and doing.insert()
again all your iterators are invalidated hence you can't run modifying loop any further.I suggest following solution which is valid and faster. Into separate std::vector copy all elements starting from
j
-th position. Delete them in map. Modify them in vector the way you like, for example by adding+1
to all keys. Insert them all back at once by.insert(begin, end)
method of a map. Clear vector of copied elements.All suggested is implemented in below code snippet:
Try it online!
Output: