查找地图c ++找不到已添加到地图中的密钥

时间:2016-06-23 01:11:07

标签: c++ dictionary fault

地图cidades开始为空。

将txt文件视为:

“city1,city2”

当城市不在地图中时,它应该为城市添加一个随机数,即计数

以下是代码:

 int i,cont = 0;   // i is used as a flag and count do add a key reference when I add a new element in the map
 string line;      // used to get everything  untill the comma

 map<string,int> cidades;    // map of cities and their references .. like cidades<"Silicon Valley", 1>

 ifstream arquivoTexto ("text.txt");  

 if (arquivoTexto.is_open()) {   // open file
    while (getline (arquivoTexto,line)){  // while EOF is false

        stringstream element(line);  i = 1;  // i is always 1 when checking a new line

 while(getline(element, line, ',')){     // line is the string untill the comma
            if(i == 1) {    // i = 1 means the current line is the city one

                std::map<std::string, int>::iterator it = cidades.find(line);   // try to find the current city in the map

                if(cidades.empty()){  // insert first time because map is empty 
                    cidades.insert(pair<string,int>(line,cont));
                }
                else if(it == cidades.end()){    // insert because is not in the map
                    cidades.insert(pair<string,int>(line,cont));
                    c1 = cont;
                }else{                      // get the key because is already in the map
                    c1 = cidades.at(line);
                }
            } else if( i == 2) {
                // line is holding city 2, do the same above
            }
    cont++; i++;      // increase i to tell we are working with the next string after the comma
 }

但是当我把相同的代码放在上面的条件中时......它可以工作

string a = "teste";   // taken from the txt and added into the map
std::map<std::string, int>::iterator it = cidades.find(a);
cout << "ele: " << it->first  << " chave: " << it->second;

它会打印出teste和密钥......但是当我尝试打印内部时,如果我遇到分段错误(核心转储)。

编辑: 我的程序找不到已经在地图中的密钥。 当我比较if语句中的迭代器时,看起来没有键在地图中(即使键已经在它上面,那么它再次使用另一个整数引用添加相同的键)。那么现在我想找出另一种在地图中寻找键的方法,任何好的想法?

1 个答案:

答案 0 :(得分:0)

可能是因为line未找到,在这种情况下it将被设置为map :: end,我认为这基本上意味着它设置为&#39; NULL&#39;或者一些无效的位置,这意味着你不应该取消引用它,即:it->first(因此分段错误)(从技术上讲,如果取消引用从find返回的迭代器,当它没有取消时会发生什么?找到任何东西,是不明确的行为,即不要这样做。),

http://www.cplusplus.com/reference/map/map/find/

不要在那里cout做,在其他地方做{39}。在下面,您知道it指向有效的项目。

相关问题