c++ - "vector iterator not incrementable"set_intersection 运行时错误

标签 c++ stl stl-algorithm

为什么这段代码会导致运行时错误“vector iterator not incrementable”?

vector<string> s1, s2;

 s1.push_back("joe");
 s1.push_back("steve");
 s1.push_back("jill");
 s1.push_back("svetlana");

 s2.push_back("bob");
 s2.push_back("james");
 s2.push_back("jill");
 s2.push_back("barbara");
 s2.push_back("steve");

 sort(s1.begin(), s1.end());
 sort(s2.begin(), s2.end());

 vector<string> result;
 vector<string>::iterator it_end, it_begin;
 it_end = set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), result.begin());
 cout << int (it_end - result.begin()) << endl;
 for_each(result.begin(), result.end(), print);

最佳答案

空 vector 的

result.begin() 不是有效的输出迭代器。你需要一个 back_inserter(result)相反。

#include <iterator>
...
set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), back_inserter(result));
cout << result.size() << endl;

或者,将 result 的大小调整为至少 4,以便 vector 可以包含所有结果。

关于c++ - "vector iterator not incrementable"set_intersection 运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3477955/

相关文章:

c++ - 第一个元素的索引 > 到具有 STL::algorithm 的 vector 中的数字?

c++ - 为什么 fill_n() 不适用于 vector.reserve()?

c++ - MySQL C++ 连接器 MySQL_Prepared_Statement::getUpdateCount 错误

c++类型写特殊字符效果

c++ - 有没有办法交叉/区分 std::map 和 std::set?

c++ - 通过键值的查找函数在 map 中搜索不正确

c++ - C++ wrt 字符串中的 STL 排序函数

c++ - 在 shared_ptr 的容器上使用 C++ std::equal

c++ - C++中 float 的全精度显示?

c++ - 我一直收到语法错误,但我不确定为什么