insert()
C ++ STL中的向量函数通过在指定位置的元素之前插入新元素来帮助增加容器的大小。
它是C ++ STL中的预定义函数。
我们可以使用三种类型的语法插入值
1.通过仅提及位置和值来插入值:
vector_name.insert(pos,value);
2.通过提及位置,值和大小来插入值:
vector_name.insert(pos,size,value);
3.通过提及要插入值的位置和填充向量的迭代器,将值插入到另一个填充向量的空向量中:
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