vector insert() 函数在 C++ STL 中
C++ STL 中的 vector insert() 函数有助于通过在指定位置的元素之前插入新元素来增加容器的大小。
这是 C++ STL 中预定义的函数。
我们可以使用三种语法插入值
1. 仅提及位置和值来插入值
vector_name.insert(pos,value);
2. 提及位置、值和大小来插入值
vector_name.insert(pos,size,value);
3. 从已填充的 vector 形式的另一个空 vector 插入值,通过提及应插入值的位置和已填充 vector 的迭代器
empty_eector_name.insert(pos,iterator1,iterator2);
算法
Begin Declare a vector v with values. Declare another empty vector v1. Declare another vector iter as iterator. Insert a value in v vector before the beginning. Insert another value with mentioning its size before the beginning. Print the values of v vector. Insert all values of v vector in v1 vector with mentioning the iterator of v vector. Print the values of v1 vector. End.
范例
#include<iostream> #include <bits/stdc++.h> using namespace std; int main() { vector<int> v = { 50,60,70,80,90},v1; //declaring v(with values), v1 as vector. vector<int>::iterator iter; //declaring an iterator iter = v.insert(v.begin(), 40); //inserting a value in v vector before the beginning. iter = v.insert(v.begin(), 1, 30); //inserting a value with its size in v vector before the beginning. cout << "The vector1 elements are: \n"; for (iter = v.begin(); iter != v.end(); ++iter) cout << *iter << " "<<endl; // printing the values of v vector v1.insert(v1.begin(), v.begin(), v.end()); //inserting all values of v in v1 vector. cout << "The vector2 elements are: \n"; for (iter = v1.begin(); iter != v1.end(); ++iter) cout << *iter << " "<<endl; // printing the values of v1 vector return 0; }
输出
The vector1 elements are: 30 40 50 60 70 80 90 The vector2 elements are: 30 40 50 60 70 80 90
广告