C++ <vector> - emplace() Function
The C++ vector::emplace function is used to insert new element at specified position in a vector. Each insertion of element increases the vector container size by one. This may cause a reallocation when the vector size surpasses the vector capacity.
Syntax
template <class... Args> iterator emplace (const_iterator position, Args&&... args);
Parameters
position |
Specify the position in the vector where the new element need to be inserted. |
args |
Arguments forwarded to construct the new element. |
Return Value
An iterator that points to the newly emplaced element.
Time Complexity
Linear i.e, Θ(n).
Example:
In the example below, the vector::emplace function is used to insert new element at specified position in a vector MyVector.
#include <iostream> #include <vector> using namespace std; int main (){ vector<int> MyVector{10, 20, 30, 40, 50}; //insert a new element at position = 3 MyVector.emplace(MyVector.begin()+2, 100); //insert a new element at position = 3 MyVector.emplace(MyVector.begin()+2, 200); //insert a new element at the end of the vector MyVector.emplace(MyVector.end(), 300); cout<<"MyVector contains: "; for(int i=0; i< MyVector.size(); i++) cout<<MyVector[i]<<" "; return 0; }
The output of the above code will be:
MyVector contains: 10 20 200 100 30 40 50 300
Example:
Lets see another example where the vector MyVector contains string values.
#include <iostream> #include <vector> using namespace std; int main (){ vector<string> MyVector{"JAN", "APR", "MAY"}; //insert a new element at position = 2 vector<string>::const_iterator it = MyVector.emplace(MyVector.begin()+1, "MAR"); //insert a new element at position = 2 MyVector.emplace(it, "FEB"); //insert a new element at the end of the vector MyVector.emplace(MyVector.end(), "JUN"); cout<<"MyVector contains: "; for(int i=0; i< MyVector.size(); i++) cout<<MyVector[i]<<" "; return 0; }
The output of the above code will be:
MyVector contains: JAN FEB MAR APR MAY JUN
❮ C++ <vector> Library