
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Vector Insert Function in C++ STL
vector insert() function in C++ STL helps to increase the size of a container by inserting the new elements before the elements at the specified position.
It is a predefined function in C++ STL.
We can insert values with three types of syntaxes
1. Insert values by mentioning only the position and value:
vector_name.insert(pos,value);
2. Insert values by mentioning the position, value and the size:
vector_name.insert(pos,size,value);
3. Insert values in another empty vector form a filled vector by mentioning the position, where the values are to be inserted and iterators of filled vector:
empty_eector_name.insert(pos,iterator1,iterator2);
Algorithm
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.
Example
#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; }
Output
The vector1 elements are: 30 40 50 60 70 80 90 The vector2 elements are: 30 40 50 60 70 80 90
Advertisements