Question

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 ?

Was it helpful?

Solution 2

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;

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top