语句位置的不同导致的错误?

aifeifei10 2013-05-11 07:45:12
	while(getline(input,line))
{
istringstream stream(line);
string word;
bool firstword=true;
while(stream>>word)
{
map<string,string>::const_iterator map_it=trans_map.find(word);
if(map_it!=trans_map.end())
word=map_it->second; //运行成功
if(firstword)
firstword=false;
else cout<<" ";
// word=map_it->second; //运行产生错误
cout<<word;
}
cout<<endl;
}

我不明白,中间的firstword对map_it应该没有影响吧,为什么会导致不同的结果呢?
...全文
58 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
bigfog 2013-05-12
  • 打赏
  • 举报
回复
关于你的代码的说明: if(map_it!=trans_map.end()) word=map_it->second; //运行成功 //说明,这条语句执行的条件,前面if条件成立 if(firstword) firstword=false; else cout<<" "; // word=map_it->second; //运行产生错误//不管if(map_it!=trans_map.end()) 是否成立都要执行,肯定要最后出界错误
gzliudan 2013-05-12
  • 打赏
  • 举报
回复
你加上{}后,就可以发现错误是怎样产生的 下面这句当map_it已经是最后1个元素时,再调用second就会出错 // word=map_it->second; //运行产生错误
aifeifei10 2013-05-11
  • 打赏
  • 举报
回复
我加上{}试了,还是不行的,应该不是{}的问题
aifeifei10 2013-05-11
  • 打赏
  • 举报
回复
如果不加{}的话if else不是只对紧接着的那一句有影响吗?
gzliudan 2013-05-11
  • 打赏
  • 举报
回复
有影响的 你的if else语句最好用 { }分开,例如: if (...) { ...... } else { ...... }

13,824

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder相关内容讨论区
社区管理员
  • 基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧