[英]Cyclically iterating through C++ map, program crashes
我是新来的。 我是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;
}
我的程序(和上面的程序)在遍历地图一次后一直崩溃。 我不知道为什么。 我尝试查找SO和其他地方,但是找不到解决方案。
提前致谢。
考虑一下迭代器在循环中每次指向的内容。
当迭代器变得等于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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.