c++iteratorforward-list

How to keep track with std::forward_list 's first element?


I want to save an iterator of the first elements in a forward list as it and do some insert on the list. Then I want to erase the element at it. For example, in {20,30,40,50} and insert 10 at front. We get {10,20,30,40,50}. Then I want to erase 20, which means I want {10,30,40,50}. I tried to use before_begin() but it seems that it always point to the before of begin() of the list even after inserting.

#include <bits/stdc++.h>
using namespace std;
int main()
{
    forward_list<int> fl = { 20, 30, 40, 50 };
    auto it = fl.before_begin();
    fl.emplace_front(10);
    fl.erase_after(it);
    cout << "Element of the list are:" << endl;
    for (auto it = fl.begin(); it != fl.end(); ++it)
        cout << *it << " ";
    return 0;
}

Have 20,30,40,50 rather than 10,30,40,50.

Is there any way to store a inerator that after ++, it will point to the begin element.


Solution

  • I solve this problem by adding an count, counting the number inserted at front and then move iterators from begin().