#include <stdio.h>
#include <iostream>
#include <map>
#include <string>
#include <stdlib.h>
using namespace std;
class Fix
{
};
int main()
{
map<int, Fix *> m;
Fix * f = new Fix();
m.insert( make_pair( 2, f) );
m.insert( make_pair( 3, f) );
map<int, Fix *>::iterator it = m.find(2);
map<int, Fix *>::iterator it1 = m.find(2);
m.erase(it);
// Will Create problem
// m.erase(it1);
// Still value is there
// So from the map node, iterator copy its value ?
printf("%d\n", it->first);
printf("%d\n", it1->first);
}
我有一个Map包含两个条目,还有两个指向同一条目的迭代器。 使用Iterator1从地图中删除了一个条目。删除后仍然是Iterator1和Iterator2保持值。
问题
答案 0 :(得分:3)
对std::map::erase
在迭代器上使用this method具有以下效果:
从容器中删除指定的元素
对已擦除元素的引用和迭代器无效。其他引用和迭代器不受影响。
因此,在删除it1
之后,您无法使用it
,即使it1
仍可以巧合地指向“现在无效”的先前记忆。
答案 1 :(得分:0)
请标记接受的答案。
bits_international在他的解释中是正确的,将主函数中的代码更改为以下内容。
map<int, Fix *> m;
Fix * f = new Fix();
m.insert( make_pair( 2, f) );
m.insert( make_pair( 3, f) );
map<int, Fix *>::iterator it = m.find(2);
it = m.erase(it); //you can reuse it after this call
map<int, Fix *>::iterator it1 = m.find(2);
it1 = m.erase(it1); //you can reuse it1 after this call
printf("%d\n", it->first);
printf("%d\n", it1->first);