std::forward_list
is a sequential container with forward_iterators. It is a one-sided singly-linked list. To insert a value into the list you can use only the method insert_after
specifying an iterator in the range [begin(), end())
or the iterator returned by the method before_begin()
.
From the C++ Standard
5 Requires: position is before_begin() or is a dereferenceable
iterator in the range [begin(), end()).
So if you are going to append a new value to the end of a list you have to move an iterator in the position that corresponds to the last element in the list.
So this loop named range-based for loop
for (auto& _ : obj)
++b_end ;
moves step by step the iterator b_end
in the position occupied by the last element in the list. So now using the iterator you can append a new value to the list using the method insert_after
.
Consider a simple demonstrative program.
#include <iostream>
#include <forward_list>
int main()
{
std::forward_list<int> lst = { 1, 2 };
auto b_end = lst.before_begin();
for (const auto &_ : lst)
{
++b_end;
std::cout << *b_end << '\n';
}
std::cout << std::endl;
lst.insert_after(b_end, 3);
for (const auto &_ : lst) std::cout << _ << ' ';
std::cout << std::endl;
return 0;
}
The program output is
1
2
1 2 3
At first the iterator b_end
points to before the first element in the list.
auto b_end = lst.before_begin();
^^^^^^^^^^^^^^
After that in the loop that will have two iterations because the list contains only two elements the iterator at first will be moved in the position that corresponds to the first element and then in the position that corresponds to the second element.
Now using the obtained iterator we can add the value 3 after the value 2.