【问题标题】:Cyclically iterating through C++ map, program crashes循环遍历C++ map,程序崩溃
【发布时间】:2017-07-24 22:36:00
【问题描述】:

我是新来的。我是 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 和其他地方查找,但找不到解决方案。

提前致谢。

【问题讨论】:

    标签: c++


    【解决方案1】:

    想想迭代器在循环中的每个循环指向什么。

    当迭代器等于colors.end() 时,它不指向任何东西,你也不能取消引用它。

    但是你取消引用迭代器(itr-&gt;first你检查它是否等于colors.end()

    【讨论】:

    • 谢谢,我忘记了 end() 指向什么,而不是容器中的最后一个实体。我很尴尬。
    【解决方案2】:

    见 cmets:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 2015-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多