查找地图C 没有在地图中找到已经添加的密钥

find map c++ is not finding key already added in the map

本文关键字:地图 添加 密钥 查找      更新时间:2023-10-16

地图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和键...但是当我尝试在内部分段故障的情况下打印时(core倾倒)。

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

可能是因为找不到 line,在这种情况下, it将设置为map :: end,我认为这基本上意味着它设置为'null'或一些无效的位置,这意味着您不应将其解释,即:it->first(因此,分割错误)(从技术上讲,如果您在找不到任何东西时从find返回的迭代器会发生什么,是未定义的行为,即不这样做。),p> http://www.cplusplus.com/reference/map/map/find/

不要在那里执行cout,在下面的"其他"中进行,您知道it指向有效的项目。