查找地图C 没有在地图中找到已经添加的密钥
find map c++ is not finding key already added in the map
地图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
指向有效的项目。
相关文章:
- 如何使用 emplace 添加到C++中的地图
- 如何将模板函数指针作为值参数添加到地图中
- 在C++中向地图添加对对象的引用
- 是 std::make_pair 在将对象添加到地图时创建副本
- C 将类成员功能添加到地图中
- 以键作为结构的地图添加
- 了解如何使用SFML函数将数据添加到地图中
- 查找地图C 没有在地图中找到已经添加的密钥
- 使用单词键将多个行号的向量添加到我的地图中
- 如何在地图中添加值,并将向量作为值类型
- 在迭代地图时向/从地图添加/删除元素是否安全
- 添加到具有可变值的地图
- 为什么我不能<Derived>在此代码中添加shared_ptr到地图<key_type,shared_ptr<Base>>?
- 添加第三级地图
- 将新条目添加到地图列表中
- 如何将地图作为参数传递并在此方法中添加
- 如何添加到地图 <int、列表<int>>
- 无法将值添加到嵌套在地图内的向量中
- 如何找到一个特定的关键和添加值使用矢量或地图
- C++ 如何将对象添加到地图并返回对地图中新创建的对象的引用