c++c++11stlforward-list

insert element at the beginning of std::forward_list


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 ?


Solution

  • 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;