Cover Image for Forward List in C++ Manipulating Functions
137 views

Forward List in C++ Manipulating Functions

A std::forward_list in C++ is a singly-linked list container from the Standard Template Library (STL). It provides a limited set of operations compared to other containers like std::vector or std::list because it only allows forward iteration and does not support bidirectional or random access.

Here are some common manipulation functions for std::forward_list:

  1. push_front(): Inserts an element at the beginning of the list.
C++
 std::forward_list<int> myList;
 myList.push_front(42);
  1. pop_front(): Removes the first element from the list.
C++
 myList.pop_front();
  1. insert_after(): Inserts an element after a specified position (an iterator).
C++
 auto it = myList.begin();
 myList.insert_after(it, 30);
  1. emplace_after(): Constructs an element in-place after a specified position (an iterator).
C++
 auto it = myList.begin();
 myList.emplace_after(it, 55);
  1. erase_after(): Removes an element after a specified position (an iterator).
C++
 auto it = myList.begin();
 myList.erase_after(it);
  1. remove(): Removes all elements with a specified value.
C++
 myList.remove(42);
  1. remove_if(): Removes elements that satisfy a given predicate.
C++
 myList.remove_if([](int x){ return x % 2 == 0; }); // Removes even numbers
  1. splice_after(): Transfers elements from one list to another or within the same list.
C++
 std::forward_list<int> otherList = {1, 2, 3};
 auto it = myList.before_begin();
 myList.splice_after(it, otherList);
  1. merge(): Merges two sorted lists into one sorted list.
C++
 std::forward_list<int> otherList = {4, 5, 6};
 myList.sort();
 otherList.sort();
 myList.merge(otherList);
  1. reverse(): Reverses the order of elements in the list. myList.reverse();
  2. unique(): Removes consecutive duplicate elements. myList.unique();
  3. clear(): Removes all elements from the list. myList.clear();

These are some of the key manipulation functions available for std::forward_list. Keep in mind that std::forward_list is optimized for insertion and deletion at the beginning of the list, but it has limitations when it comes to random access or operations at the end of the list.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS