“vector iterator not incrementable” run-time error with set_intersection

允我心安 提交于 2019-12-07 14:33:42

问题


Why does this code result in a run-time error "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:


result.begin() of an empty vector is not a valid output iterator. You need a back_inserter(result) instead.

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

Alternatively, resize result to at least 4, so that the vector can contain all results.



来源:https://stackoverflow.com/questions/3477955/vector-iterator-not-incrementable-run-time-error-with-set-intersection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!