“vector iterator not incrementable”运行时错误与set_intersection

时间:2010-08-13 14:44:30

标签: 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);

1 个答案:

答案 0 :(得分:9)

空向量的

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,以便向量可以包含所有结果。