The insert()
function is defined in the <vector>
header and is used to add an element or elements into a vector.
The function can be used in three main ways, as discussed below.
iterator insert(iterator position, const value_type& val);
myVector.insert(position, val)
position
: an iterator that points to the position where the value is to be added.val
: the single element that needs to be added at position
.#include <iostream>#include <vector>using namespace std;int main(){vector<int> vec;vector<int>::iterator iter = vec.begin();iter = vec.insert(iter, 1);iter = vec.insert(iter, 2);int vecSize = vec.size();cout << vecSize << endl;for(int i = 0; i < 2; i++){cout << vec.at(i) << " ";}cout << endl;return 0;}
void insert(iterator position, size_type n, const value_type& val);
myVector.insert(position, size, val)
position
: an iterator that points to the position where the value is to be added.
size
: the number of times the element is added.
val
: the single element that needs to be added at position
.
#include <iostream>#include <vector> // first include <vector>using namespace std;int main(){//decleration of int vectorvector<int> vec;vec.insert(vec.end(), 1, 1);vec.insert(vec.end(), 2, 2);vec.insert(vec.end(), 3, 3);int vecSize = vec.size();cout << vecSize << endl;for(int i = 0; i < vecSize; i++){cout << vec.at(i) << " ";}cout << endl;return 0;}
In this syntax, we can add elements from one vector into another.
void insert(iterator position, InputIterator first, InputIterator last);
myVector.insert(position, iter1, iter2)
position
: an iterator that points to the position where the value is to be added.
iter1
: starting position of the elements that need to be added.
iter2
: ending position of the elements that need to be added.
#include <iostream>#include <vector> // first include <vector>using namespace std;int main(){vector<int> vec1 = {0, 1, 2, 3};vector<int> vec2;vec2.insert(vec2.begin(), vec1.begin(), vec1.end());int vec2Size = vec2.size();cout << vec2Size << endl;for(int i = 0; i < vec2Size; i++){cout << vec2.at(i) << " ";}cout << endl;return 0;}
Every syntax returns an iterator that points to the newly inserted element or the first of the newly inserted elements.