我无法理解为什么这段代码会因segfault而失败:
#include <cstdlib>
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main(int argc, char** argv) {
map <string, string> temp;
map <string, string>::iterator it;
取值
string text =“”;
string thatChange =“”;
string whatChange =“”;
getline (cin, text);
while (true)
{
getline (cin, thatChange);
if (thatChange == "-1")
break;
getline (cin, whatChange);
temp.insert(pair <string, string> (thatChange, whatChange));
}
for (int i = 0; i < temp.size(); i++)
{
string thatChange = it->first ; // thatChange
string whatChange = it->second; // whatChange
it++;
int index = text.find(thatChange);
text.erase(index, thatChange.size());
text.insert(index, whatChange);
}
cout << "text\n"<< text;
return 0;
}
UPD: 调试器说:
No source available for "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string() at 0x7ffff7b75928"
答案 0 :(得分:4)
string thatChange = it->first ;
这条线唤起IN。到目前为止,it
从未初始化。你应该按如下方式初始化:
it = tmp.begin();
并迭代使用地图的所有元素:
for (map<string, string>::const_iterator f = temp.begin(), e = temp.end;
f != e;
++f) {
// ....
}
答案 1 :(得分:0)
FWIW代码片段可以编译并运行VS2010,所以如果你遇到错误,问题可能就在其他地方。