The C++ vector::emplace_back() function extends the vector by adding a new element. Reallocation occurs if additional space is required. Similar to dynamic arrays, vectors can automatically resize when an item is added or removed.The time complexity of the emplace_back() function is constant.
The container manages the vector storage. Moreover, one can add an element to the end of a vector by using the emplace_back() function. It doesn't produce a temporary object. The object is directly created in the vector. As a result, efficiency is increased. The complexity of the emplace_back() function is constant.
SyntaxFollowing is the syntax for C++ vector::emplace_back() Function −
void emplace_back (Args&&... args);Parameters
args − It indicates the argumrnt that is forwarded to construct the new element.
Example 1Let's consider the following example, where we are going to use integer vector used with the emplace_back() function.
#include <iostream> #include <vector> using namespace std; int main(){ vector<int>myvector; myvector.emplace_back(11); myvector.emplace_back(22); myvector.emplace_back(33); for (auto x = myvector.begin(); x != myvector.end(); ++x) cout<< ' ' << *x; return 0; }Output
When we compile and run the above program, this will produce the following result −
11 22 33Example 2
Considering the another scenario, where we are going to take the string vector and use it with emplace_back() function.
#include <iostream> #include <vector> #include <string> using namespace std; int main(){ vector<string>myvector; myvector.emplace_back("Welcome"); myvector.emplace_back("To"); myvector.emplace_back("The World.!"); for(auto x =myvector.begin(); x != myvector.end(); ++x) cout<< ' ' << *x; return 0; }Output
On running the above program, it will produce the following result −
Welcome To The World.!Example 3
In the following example, we are going to use the character vector with the emplace_back() function.
#include <iostream> #include <vector> #include <string> using namespace std; int main(){ vector<char>myvector; myvector.emplace_back('T'); myvector.emplace_back('P');; for(auto x =myvector.begin(); x != myvector.end(); ++x) cout<< ' ' << *x; return 0; }Output
On running the above program, it will produce the following result −
T P
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