Reputation: 2590
I want to remove element from std::forward_list
and insert it to the beginning of list
But there is no insert method ... It just has insert_after
!
How can I insert element at the beginning of std::forward_list
?
Upvotes: 1
Views: 1008
Reputation: 43314
Use std::forward_list::push_front
.
Example:
// forward_list::push_front
#include <iostream>
#include <forward_list>
using namespace std;
int main ()
{
forward_list<int> mylist = {77, 2, 16};
mylist.push_front (19);
mylist.push_front (34);
std::cout << "mylist contains:";
for (int& x: mylist) std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
Output: mylist contains: 34 19 77 2 16
Upvotes: 6
Reputation: 310950
You can use method
push_front
to insert an element at the beginning of the list
Another approach is to use method insert_after
.
Here is an example of using the both methods
std::forward_list<int> l;
l.push_front( 1 );
l.insert_after( l.cbefore_begin(), 0 );
for ( int x : l ) std::cout << x << ' ';
std::cout << std::endl;
Upvotes: 2