c++ - 循环迭代 C++ 映射,程序崩溃

标签 c++

我是 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/

相关文章:

c++ - 发送矩阵的行和列,MPI_SEND

c++ - 使用 exec 在 C++ 中执行 shell 命令

c++ - QString 到 const std::string

c++ - 对 boost::locale:conv::between 的 undefined reference

C# COM 对象和 CreateDispatch

java - 从外部应用程序的屏幕获取数据

c++ - 提供基类构造函数

c++ - 快速排序/vector/分区问题

c++ - 我应该如何正确播种 C++11 std::default_random_engine?

c++ - 从 Windows 上的文件中读取多个分隔的 protobuf 消息