我是新手。我是C 的迭代器(或STL)的新手。我正在尝试以循环方式遍历地图的键。因此,我们从一开始就开始阅读,然后进入末尾,然后再次回到开始。下面的代码简化了我程序的相关部分:
#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;
}
我的程序(以及上述程序)在迭代一次地图后不断崩溃。我无法弄清楚原因。我尝试抬头和其他地方,找不到解决方案。
预先感谢。
考虑迭代器指向每个曲线的指向。
当迭代器变得等于 colors.end()
时,它没有指向任何东西,因此您不允许它解除。
但是您在之前删除了迭代器(itr->first
)您检查它是否等于colors.end()
。
请参阅注释:
for(int i=0; i<10; i++) {
std::cout << itr->first << std::endl;//Problematic..
if(itr == colors.end())
itr = colors.begin();
else
itr++; //If this increment results to an `end()` iterator
}
您是无条件访问迭代器而不检查它是否是end()
迭代器。在访问指向的元素之前,您应该检查迭代器不是end()
迭代器。
您可以将循环更改为:
for(int i=0; i<10; i++){ // Loop more than entries in map
if( itr != colors.end() ){
std::cout<< itr->first << std::endl;
++itr;
}
else
itr = colors.begin(); //start from beginning
}
demo