问题描述
- C++ STL的merge函数越界
- 小白想问问大神,用merge函数时一直报错,说iterator越界
代码如下:
#include
#include
#include
#include
using namespace std;void display(vector &v)
{
for (vector::iterator it = v.begin(); it != v.end();++it)
{
cout<<*it<<endl;
}
cout<<endl;
}int main()
{
vector v1v2v3;
for (int i =0; i<=2 ;++i)
{
v1.push_back(i);
}
for (int i =3; i<=7 ;++i)
{
v2.push_back(i);
}
for (int i =8; i<=10 ;++i)
{
v3.push_back(i);
}
merge(v1.begin()v1.end()v2.begin()v2.end()v3.begin());
display(v3);
system(""pause"");
return 0;
}谢谢大神
解决方案
C++ merge函数
[STL] list merge 函数
[STL] list merge 函数
解决方案二:
v3需要resize一下才行
PS:而且merge(v1.begin()v1.end()v2.begin()v2.end()v3.begin());这样用的话,v3前面的三个元素会被覆盖掉
#include<iostream>#include<vector>#include<algorithm> using namespace std;void display(vector<int> &v){ for (vector<int>::iterator it = v.begin(); it != v.end();++it) { cout<<*it<<endl; } cout<<endl;}int main(){ vector<int> v1v2v3; for (int i =0; i<=2 ;++i) { v1.push_back(i); } for (int i =3; i<=7 ;++i) { v2.push_back(i); } for (int i =8; i<=10 ;++i) { v3.push_back(i); } v3.resize(11); merge(v1.begin()v1.end()v2.begin()v2.end()v3.begin()); display(v3); system(""pause""); return 0;}
时间: 2024-10-31 00:12:01