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 example below, the forward_list::emplace_after function is used to insert new element at specified position in a forward_list flist.
#include <iostream> #include <forward_list> using namespace std; int main (){ forward_list<int> flist{10, 20, 30, 40, 50}; forward_list<int>::iterator it; //insert a new element at position = 3 it = flist.begin(); advance(it, 2); flist.emplace_after(it, 100); //insert a new element at position = 4 flist.emplace_after(it, 200); cout<<"flist contains: "; cout<<"flist contains: "; for(it = flist.begin(); it != flist.end(); it++) cout<<*it<<" "; return 0; }
The output of the above code will be:
flist contains: 10 20 30 200 100 40 50
Example:
Lets see another example where the forward_list called flist contains string values.
#include <iostream> #include <forward_list> using namespace std; int main (){ forward_list<string> flist; forward_list<string>::iterator it; it = flist.before_begin(); //insert new element in the forward_list flist.emplace_after(it, "JAN"); flist.emplace_after(it, "FEB"); flist.emplace_after(it, "MAR"); flist.emplace_after(it, "APR"); flist.emplace_after(it, "MAY"); flist.emplace_after(it, "JUN"); cout<<"flist contains: "; for(it = flist.begin(); it != flist.end(); it++) { cout<<*it<<" "; } return 0; }
The output of the above code will be:
flist contains: JUN MAY APR MAR FEB JAN
❮ C++ <forward_list> Library