Forward list

As the name suggests, the forward_list class is like the list class, but it only allows items to insert and remove items from the front of the list. It also means that the iterators used with the class can only be incremented; the compiler will refuse to allow you to decrement such an iterator. The class has a subset of the methods of list, so it has the push_front, pop_front, and emplace_front methods, but not the corresponding _back methods. There are some other methods that it implements, and, because the list items can only be accessed in a forward direction, it means that insertions will occur after an existing item, and hence the class implements insert_after and emplace_after.

Similarly, you can remove items at the beginning of the list (pop_front) or after a specified item (erase_after), or tell the class to iterate in a forward direction through the list and remove items with a specific value (remove and remove_if):

    forward_list<int> euler { 2,7,1,8,2,8 }; 
euler.push_front(-1); // { -1,2,7,1,8,2,8 }
auto it = euler.begin(); // iterator points to -1
euler.insert_after(it, -2); // { -1,-2,2,7,1,8,2,8 }
euler.pop_front(); // { -2,2,7,1,8,2,8 }
euler.remove_if([](int i){return i < 0;});
// { 2,7,1,8,2,8 }

In the preceding code, euler is initialized with the digits of Euler's number and a value of -1 is pushed to the front. Next, an iterator is obtained that points to the first value in the container; that is, to the position of the value of -1. A value of -2 is inserted after the position of the iterator; that is, -2 is inserted after the value of -1. The last two lines show how to remove items; pop_front removes the item at the front of the container and remove_if will remove items that satisfy the predicate (in this case when the item is less than zero).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset