//by 鸟哥 合并vector的方法
//有疑问请留言或加群 1032082534
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
void printVector(const vector<int> &v)
{
for (int i = 0; i < v.size(); ++i){
cout << v[i] << " ";
}
cout<<endl;
}
int main()
{
//1、merge
vector<int> v1 = {1,2,3,4,5};
vector<int> v2 = {1,4,5,6,7};
vector<int> v3;
v3.resize(v1.size()+v2.size());//合并前需要准备空间
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
printVector(v3);//1 1 2 3 4 4 5 5 6 7
vector<int> v4;//使用back_inserter不用提前准备空间
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(v4));
printVector(v4);//1 1 2 3 4 4 5 5 6 7
//2、insert
v2.insert(v2.end(),v1.begin(),v1.end());
printVector(v2);//1 4 5 6 7 1 2 3 4 5
return 0;
}
运行结果:
1 1 2 3 4 4 5 5 6 7
1 1 2 3 4 4 5 5 6 7
1 4 5 6 7 1 2 3 4 5
来源:CSDN
作者:鸟哥01
链接:https://blog.csdn.net/sinat_18811413/article/details/104599211