forward_list emplace_after() and emplace_front() in C++ STL
- The forward_list::emplace_after() is a builtin function in C++ STL which is used to insert a new element after the element at position specified in the argument. This insertion of the new element increases the size of the container by one.
Syntax:
forward_list_name.emplace_after(iterator position, elements)
Parameters: The function accepts two mandatory parameter which are described below:
- position: it specifies the iterator which points to the position in the container after which new element is to be inserted.
- element: specifies the new element to be inserted after the position.
Return Value :This function returns an iterator that points to the newly inserted element.
Below program illustrates the above mentioned function:
// C++ program to illustrate the
// forward_list::emplace_after() function
#include <forward_list>
#include <iostream>
using
namespace
std;
int
main()
{
forward_list<
int
> fwlist = { 1, 2, 3, 4, 5 };
auto
it_new = fwlist.before_begin();
// use of emplace_after function
// inserts elements at positions
it_new = fwlist.emplace_after(it_new, 8);
it_new = fwlist.emplace_after(it_new, 10);
// cout << "The elements are: "
for
(
auto
it = fwlist.cbegin(); it != fwlist.cend(); it++) {
cout << *it <<
" "
;
}
return
0;
}
Output:
The elements are: 8 10 1 2 3 4 5
- The forward_list::emplace_front() is a built-in function in C++ which is used to insert a new element at the beginning of the forward_list just before the first element. This increases the size of container by one.
Syntax:
forward_list_name.emplace_front(elements)
Parameters: The function accepts one mandatory parameter element which is to be inserted at the start of the container.
Return Value: It returns nothing.
Below program illustrates the above function.
// C++ program to illustrate the
// forward_list::emplace_front() function
#include <forward_list>
#include <iostream>
using
namespace
std;
int
main()
{
forward_list<
int
> fwlist = { 1, 2, 3, 4, 5 };
// use of emplace_front function
// inserts elements at front
fwlist.emplace_front(8);
fwlist.emplace_front(10);
cout <<
"Elements are: "
;
// Auto iterator
for
(
auto
it = fwlist.cbegin(); it != fwlist.cend(); it++) {
cout << *it <<
" "
;
}
return
0;
}
Output:
Elements are: 10 8 1 2 3 4 5
Please Login to comment...