Insert elements in vector using vector::insert() | C++ STL

C++ STL vector::insert() function: Here, we are going to learn how to insert elements in vector using vector::insert() using C++ STL (Standard Template Library)?
Submitted by Vivek Kothari, on November 11, 2018

One way of inserting elements in the vector is by using push_back() function, it simply inserts the new item at the back of the vector and increases its size by 1. In this article, we are going to discuss other methods of inserting the elements in the vector.

Syntax:

    VectorName.insert (position, value);    

Here, position is the iterator which specifies the position where you want to insert the element and value is element you want to insert.

Example 1:

#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	// initialising the vector 
	vector<int> myvec{ 10, 20, 30, 40, 50 }; 

	//myvec.begin() returns the iterator which points to element 10
	//(myvec.begin() + 2) points 2 position ahead of element 10
	myvec.insert(myvec.begin()+2,25);

	cout << "Vector elements after inserting 25 : ";  
	for (vector<int>::iterator it = myvec.begin(); it != myvec.end(); it++) 
		cout << *it << " "; 

	cout<<endl;

	//it insert the element at the front of vector
	myvec.insert(myvec.begin(),5);

	cout << "Vector elements after inserting 5 : ";  
	for (vector<int>::iterator it = myvec.begin(); it != myvec.end(); it++) 
		cout << *it << " "; 

	return 0; 
}

Output

Vector elements after inserting 25 : 10 20 25 30 40 50
Vector elements after inserting 5 : 5 10 20 25 30 40 50

Note: If you want to add element more than once at specified position than you can use the following syntax:

    VectorName.insert(position, size, value);

Here, size is the parameter in the insert function which specifies the number of times a specified value is inserted.

Example 2:

#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
	// initialising the vector 
	vector<int> myvec{ 10, 20, 30, 40, 50 }; 

	//insert the element at the front of vector 3 times
	myvec.insert(myvec.begin(),3,5);

	cout << "Vector elements after inserting 5 three times: ";  
	for (vector<int>::iterator it = myvec.begin(); it != myvec.end(); it++) 
		cout << *it << " "; 

	return 0; 
}

Output

    Vector elements after inserting 5 three times: 5 5 5 10 20 30 40 50

Related Tutorials




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.