The C++ vector::emplace() function is used to insert new element at specified location in a vector. The size of the vector container increases by one with each element insertion. When the vector size is greater than the vector capacity, this might result in a reallocation.The time complexity of the emplace() function is linear.
Because vectors use an array as their underlying storage. When inserting elements other than the vector end, makes the container to shift all the elements that were after position by one to the new positions. The complexity of the emplace() function is linear.
SyntaxFollowing is the syntax for C++ vector::emplace() Function −
iterator emplace (const_iterator position, Args&&... args);Parameters
Let's consider the following example, where we are going to use the emplace() function and inserting the new element to the vector.
#include <iostream> #include <vector> int main (){ std::vector<int> tutorial = {11,22,33}; auto a = tutorial.emplace ( tutorial.begin()+1); tutorial.emplace ( a, 44); std::cout << "Elements are:"; for (auto& x: tutorial) std::cout << ' ' << x; std::cout << '\n'; return 0; }Output
When we compile and run the above program, this will produce the following result −
Elements are: 11 44 0 22 33Example 2
Considering the another scenario, where we are going to increase the vector by adding the string into the vector.
#include <iostream> #include<vector> using namespace std; int main(){ vector<string> myvector{"PORSCHE","BUCATI","BENTLY"}; myvector.emplace(myvector.begin()+1,"RS7"); for(int i=0;i<myvector.size();i++) std::cout<< myvector[i] << " "; return 0; }Output
On running the above program, it will produce the following result −
PORSCHE RS7 BUCATI BENTLYExample 3
In the following example, we are going to insert the two different elements in the same position.
#include <iostream> #include <vector> using namespace std; int main (){ vector<int> tutorial{111,222,333,444}; tutorial.emplace(tutorial.begin()+1, 555); tutorial.emplace(tutorial.begin()+1, 666); cout<<"Elements are: "; for(int i=0; i< tutorial.size(); i++) cout<<tutorial[i]<<" "; return 0; }Output
On running the above program, it will produce the following result −
Elements are: 111 666 555 222 333 444Example 4
Looking into the following example, where we are going to use the emplace() function and inserting the element at the end of the vector.
#include <iostream> #include <vector> using namespace std; int main (){ vector<int> tutorial{111,222,333,444}; tutorial.emplace(tutorial.end(), 555); cout<<"Elements are: "; for(int i=0; i< tutorial.size(); i++) cout<<tutorial[i]<<" "; return 0; }Output
On running the above program, it will produce the following result −
Elements are: 111 222 333 444 555
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4