2
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!

Joseph
  • 12,678
  • 19
  • 76
  • 115
  • 1
    surely you mean `if (it!=strings.end()) std::cout <<*it<<" is found\n";` ? – Flexo Mar 07 '12 at 09:20
  • Sorry, I shouldn't have used the word "found"; I just wanted to print what the value that the iterator ended up at was, not trying to imply that the string `s` is actually found in this vector (although that is ultimately what I want to do). – Joseph Mar 07 '12 at 09:21

1 Answers1

6

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?

Vite Falcon
  • 6,575
  • 3
  • 30
  • 48
  • 1
    Ah, this is precisely the issue. When inserting, I do not know whether or not the new string is in the vector of strings already; in fact, if it is, I don't want to add it. Adding in a check to see if the iterator was the end of the vector fixed my issue. Thanks! – Joseph Mar 07 '12 at 09:26