给定两个向量,我们必须在一个向量的末尾附加一个向量的所有元素。
要将向量的元素插入/附加到另一个向量,我们使用vector :: insert()函数。
读取模式:C ++ STL vector :: insert()函数
语法:
//从其他容器插入元素 vector::insert(iterator position, iterator start_position, iterator end_position);
参数:迭代器位置,迭代器start_position,迭代器end_position –迭代器位置是使用向量的迭代器的索引,其中要添加的元素,start_position,迭代器end_position是另一个容器的迭代器,其值将插入到当前向量中。
返回值: void –不返回任何内容。
示例
Input:
vector<int> v1{ 10, 20, 30, 40, 50 };
vector<int> v2{ 100, 200, 300, 400 };
//将向量v2的元素附加到向量v1-
v1.insert(v1.end(), v2.begin(), v2.end());
Output:
v1: 10 20 30 40 50 100 200 300 400
v2: 100 200 300 400//C ++ STL程序将向量附加到向量
#include <iostream>
#include <vector>
using namespace std;
int main(){
//向量声明
vector<int> v1{ 10, 20, 30, 40, 50 };
vector<int> v2{ 100, 200, 300, 400 };
//打印元素
cout << "before appending..." << endl;
cout << "size of v1: " << v1.size() << endl;
cout << "v1: ";
for (int x : v1)
cout << x << " ";
cout << endl;
cout << "size of v2: " << v2.size() << endl;
cout << "v2: ";
for (int x : v2)
cout << x << " ";
cout << endl;
//将向量v2的元素附加到向量v1-
v1.insert(v1.end(), v2.begin(), v2.end());
cout << "after appending..." << endl;
cout << "size of v1: " << v1.size() << endl;
cout << "v1: ";
for (int x : v1)
cout << x << " ";
cout << endl;
cout << "size of v2: " << v2.size() << endl;
cout << "v2: ";
for (int x : v2)
cout << x << " ";
cout << endl;
return 0;
}输出结果
before appending... size of v1: 5 v1: 10 20 30 40 50 size of v2: 4 v2: 100 200 300 400 after appending... size of v1: 9 v1: 10 20 30 40 50 100 200 300 400 size of v2: 4 v2: 100 200 300 400