“向量迭代器不可增加"set_intersection 的运行时错误 [英] "vector iterator not incrementable" run-time error with set_intersection

查看:25
本文介绍了“向量迭代器不可增加"set_intersection 的运行时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

result.begin() 空向量不是有效的输出迭代器.你需要一个 back_inserter(result) 代替.

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;

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

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

这篇关于“向量迭代器不可增加"set_intersection 的运行时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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