问题
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