[英]Cyclically iterating through C++ map, program crashes
I am new to SO. 我是新来的。 I am new to iterators (or rather STL) in C++.
我是C ++中迭代器(或更确切地说是STL)的新手。 I am trying to iterate through the keys of a map in a cyclic manner.
我正在尝试以循环方式遍历地图的键。 So, we start reading from the start, proceed onto the end, and then go back to the start again.
因此,我们从头开始阅读,一直到结尾,然后再次回到头。 The code below is a simplification of the relevant portion of my program:
下面的代码是我程序相关部分的简化:
#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;
}
My program (and the above program) keeps crashing after iterating through the map once. 我的程序(和上面的程序)在遍历地图一次后一直崩溃。 I am not able to figure out why.
我不知道为什么。 I tried looking up on SO and elsewhere and couldn't find a solution.
我尝试查找SO和其他地方,但是找不到解决方案。
Thanks in advance. 提前致谢。
Think about what the iterator points to for each go around the loop. 考虑一下迭代器在循环中每次指向的内容。
When the iterator becomes equal to colors.end()
, it doesn't point to anything and you're not allowed to dereference it. 当迭代器变得等于
colors.end()
,它不指向任何内容,并且您不可以对其取消引用。
But you dereference the iterator ( itr->first
) before you check whether it is equal to colors.end()
. 但是, 在检查迭代器(
itr->first
)是否等于colors.end()
之前 ,请先取消对其进行引用。
See comments: 看评论:
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
}
You are unconditionally accessing the iterator without checking if it's an end()
iterator. 您无条件访问迭代器,而无需检查它是否为
end()
迭代器。 You should check that the iterator isn't an end()
iterator before you access the element it points to. 在访问它所指向的元素之前,应检查迭代器是否不是
end()
迭代器。
You can change your loop to: 您可以将循环更改为:
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.