简体   繁体   English

C ++:为什么取消引用此向量迭代器segfault?

[英]C++: Why does dereferencing this vector iterator segfault?

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. 第二个插入将输出“找到[firststring]”,然后输出段错误。 If I comment out the if/cout line, I can repeatedly call and no segfaults occur. 如果我注释掉if / cout行,则可以重复调用并且不会发生段错误。

I've also tried doing something like std::string tmp=*it; 我也尝试过做类似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 (ie, if(*it==s) , which is segfaulting just like the above two examples). 虽然打印不是什么大问题,但我真正要做的是检查在Lower_bound找到的位置处的字符串是否与尝试插入的字符串相同(即if(*it==s) ,就像上面的两个示例一样,这是段错误。

What am I missing here? 我在这里想念什么?

Thanks! 谢谢!

Check for the condition if it == strings.end() , if it is don't print it. 检查条件是否it == strings.end() ,如果不打印则为条件。 This could cause the issue. 这可能会导致问题。 Are you sure the string you're trying to check is in the vector of strings? 您确定要检查的字符串在字符串向量中吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM