关于迭代器问题
程序报错: expression:map/set iterator not incrementable
我创建了一个map<int, int> , 想删除值为1的键值对,恰巧第一个键值对就符合要求。我猜想应该是迭代器跨界了。
附上代码:
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<int, int> map1;
map1 = 1;
map1 = 0;
map1 = 0;
map1 = 1;
map1 = 1;
map1 = 1;
map1 = 0;
map1 = 1;
map1 = 0;
map1 = 0;
map1 = 1;
for (map<int, int>::iterator itor = map1.begin(); itor != map1.end(); itor++)
{
int key = itor->first;
int value = itor->second;
//如果键值对的值为1,则删除此键值对
if (value == 1)
{
itor = map1.erase(itor);
itor--;
continue;
}
cout << "key = " << key << ", value = " << value << endl;
}
return 0;
} 本帖最后由 傻眼貓咪 于 2022-6-2 17:22 编辑
自行删除解答 #include <iostream>
#include <map>
using namespace std;
int main()
{
map<int, int> map1;
map1 = 1;
map1 = 0;
map1 = 0;
map1 = 1;
map1 = 1;
map1 = 1;
map1 = 0;
map1 = 1;
map1 = 0;
map1 = 0;
map1 = 1;
for (map<int, int>::iterator itor = map1.begin(); itor != map1.end(); )
{
//如果键值对的值为1,则删除此键值对
if (itor->second == 1)
{
itor = map1.erase(itor);
}
else
{
cout << "key = " << itor->first << ", value = " << itor->second << endl;
itor++;
}
}
return 0;
}
页:
[1]