C ++:为什么解引用这个向量迭代器segfault? [英] C++: Why does dereferencing this vector iterator segfault?

查看:143
本文介绍了C ++:为什么解引用这个向量迭代器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);
}

尝试使用此功能时,第二个插入将输出[firststring] is found,然后segfault。如果我注释掉if / cout行,我可以反复调用,没有segfaults发生。

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.

我也尝试过像 std :: string tmp = * it; ,然后segfault那条线。虽然打印不是一个巨大的交易,我真正想做的是检查在lower_bound找到的位置的字符串是否与尝试插入的字符串相同(即 if( * it == s),这是像上面两个例子的segfaulting)。

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).

我在这里缺少什么?

谢谢!

推荐答案

检查 it == strings.end(),如果是不打印它。这可能会导致问题。您确定要检查的字符串是否在字符串向量中?

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?

这篇关于C ++:为什么解引用这个向量迭代器segfault?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆