C++: Why does dereferencing this vector iterator segfault?

只愿长相守 提交于 2019-12-13 16:24:15

问题


void insert_string( std::vector<std::string> & strings, const std::string &s )
{

    std::vector<std::string>::iterator it=lower_bound(strings.begin(),strings.end(),s);
    if(strings.size()>0) std::cout<<*it<<" is found\n"; // ****
    strings.insert(it,s);
}

When attempting to use this function, the first insertion goes fine. The second insertion will output "[firststring] is found" and then segfault. If I comment out the if/cout line, I can repeatedly call and no segfaults occur.

I've also tried doing something like std::string tmp=*it; which will then segfault on that line. While printing is not a huge deal, what I'm really trying to do is check if the string at the position found by lower_bound is the same as the string that is trying to be inserted (i.e., if(*it==s), which is segfaulting just like the above two examples).

What am I missing here?

Thanks!


回答1:


Check for the condition if it == strings.end(), if it is don't print it. This could cause the issue. Are you sure the string you're trying to check is in the vector of strings?



来源:https://stackoverflow.com/questions/9598621/c-why-does-dereferencing-this-vector-iterator-segfault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!