The following program will be demonstrated and explained.
#include <forward_list> needs to include the header file
template <typename T>
void print(T Begin, T end)
{
for (T i = Begin; i != end; ++i)
{
std::cout << *i << std::endl;
}
std::cout << std::endl;
}
int main()
{
std::forward_list<int> obj(5); declares a one-way linked list that currently has five elements
int temp = 0;
for (auto i = obj.begin(); i != obj.end(); i++)
{
obj.push_front(temp); equivalent to head insertion method
temp++;
}
for (auto i = obj.begin(); i != obj.end(); i++)
{
std::cout << *i << std::endl; Traverse printing
}
struct std::forward_iterator_tag This iterator is a one-way iterator that can only be used from the beginning and supports the ++ * = operator
auto it = obj.begin(); accepts head iterator
*it = 123; assign value 123
it++; points to the next iterator
*it = 124; assign value 124
obj.pop_front(); Head element pops up
obj.clear(); Clear all elements of the linked list
print(obj.begin(), obj.end());
system("pause");
return 0;
}