C++ <forward_list> - emplace_after() Function
The C++ forward_list::emplace_after function is used to insert new element at specified position in a forward_list. Each insertion of element increases the forward_list container size by one.
Syntax
template <class... Args> iterator emplace_after (const_iterator position, Args&&... args);
Parameters
position |
Specify the position in the forward_list 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
Constant i.e, Θ(1).
Example:
In the below example, the forward_list::emplace_after function is used to insert new element at specified position in a forward_list f_list.
#include <iostream> #include <forward_list> using namespace std; int main (){ forward_list<int> f_list{10, 20, 30, 40, 50}; forward_list<int>::iterator it; //insert a new element at position = 3 it = f_list.begin(); advance(it, 2); f_list.emplace_after(it, 100); //insert a new element at position = 4 f_list.emplace_after(it, 200); cout<<"f_list contains: "; cout<<"f_list contains: "; for(it = f_list.begin(); it != f_list.end(); it++) cout<<*it<<" "; return 0; }
The output of the above code will be:
f_list contains: 10 20 30 200 100 40 50
Example:
Lets see another example where the forward_list called f_list contains string values.
#include <iostream> #include <forward_list> using namespace std; int main (){ forward_list<string> f_list; forward_list<string>::iterator it; it = f_list.before_begin(); //insert new element in the forward_list f_list.emplace_after(it, "JAN"); f_list.emplace_after(it, "FEB"); f_list.emplace_after(it, "MAR"); f_list.emplace_after(it, "APR"); f_list.emplace_after(it, "MAY"); f_list.emplace_after(it, "JUN"); cout<<"f_list contains: "; for(it = f_list.begin(); it != f_list.end(); it++) { cout<<*it<<" "; } return 0; }
The output of the above code will be:
f_list contains: JUN MAY APR MAR FEB JAN
❮ C++ <forward_list> Library