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]」,然後segfault。如果我註釋掉if/cout行,我可以重複調用並且不會發生段錯誤。C++:爲什麼取消引用這個向量迭代器段錯誤?
我也試過做一些像std::string tmp=*it;
那樣會在那條線上發生段錯誤。雖然打印並不是什麼大問題,但我真正想要做的是檢查lower_bound找到的位置上的字符串是否與嘗試插入的字符串相同(即,if(*it==s)
,它是像段以上兩個例子)。
我在這裏錯過了什麼?
謝謝!
當然你的意思是if(it!= strings.end())std :: cout << * it <<「找到了\ n」;'? – Flexo 2012-03-07 09:20:30
對不起,我不應該使用「找到」一詞;我只是想打印迭代器的價值是什麼,而不是試圖暗示字符串's'實際上是在這個向量中找到的(儘管這最終是我想要做的)。 – Joseph 2012-03-07 09:21:56