我是 SO 的新手。我是 C++ 中的迭代器(或者更确切地说是 STL)的新手。我正在尝试以循环方式遍历 map 的键。所以,我们从头开始阅读,一直读到最后,然后再回到开头。下面的代码是我程序相关部分的简化:
#include<iostream>
#include<map>
using namespace std;
int main(int argc, char* argv[])
{
map<const char*, int> colors;
colors = { { "RED", 1 },
{ "YELLOW", 2 },
{ "GREEN", 3 },
{ "ORANGE", 4 },
{ "CYAN", 5 } };
map<const char*, int>::iterator itr = colors.begin();
for(int i=0; i<10; i++) // Loop more than entries in map
{
cout<<itr->first<<endl;
if(itr==colors.end())
itr = colors.begin(); //start from beginning
else
itr++;
}
return 0;
}
我的程序(和上面的程序)在遍历 map 一次后一直崩溃。我不知道为什么。我尝试查找 SO 和其他地方,但找不到解决方案。
提前致谢。
最佳答案
想想每次循环时迭代器指向什么。
当迭代器等于 colors.end()
时,它不指向任何东西,您不能取消引用它。
但您在检查迭代器 (itr->first
) 是否等于 colors.end()
之前取消引用它。
关于c++ - 循环迭代 C++ 映射,程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42602226/