【发布时间】:2016-06-23 01:11:07
【问题描述】:
地图城一开始是空的。
将 txt 文件视为:
“城市1,城市2”
当城市不在地图中时,它应该添加一个随机数,即计数的城市
代码如下:
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 语句中比较迭代器时,它看起来好像没有键在地图中(即使键已经在它上面,然后它再次添加相同的键和另一个整数引用)。所以现在我正在尝试找出另一种在地图中查找键的方法,有什么好主意吗?
【问题讨论】:
-
gdb -ex run --args ./name_of_your_program arguments_if _needed,bt,info locals, ... -
请编辑您的问题并提供minimal reproducible example。
-
您尝试打印
it->first和it->second,无论是否找到任何内容。这不可能。 -
@EduardoHumberto 如何更改
if使其仍尝试访问it->first来解决您访问it->first的问题,而无需先确保迭代器引用任何内容?跨度> -
if(cidades.empty){if将始终触发。你的意思是if(cidades.empty())?
标签: c++ dictionary fault