forward_list::before_begin() in C++ STL


In this article we will be discussing the working, syntax and examples of forward_list::before_begin() function in C++.

What is a Forward_list in STL?

Forward list are sequence containers that allow constant time insert and erase operations anywhere within the sequence. Forward list are implement as a singly-linked lists. The ordering is kept by the association to each element of a link to the next element in the sequence.

What is forward_list::before_begin()?

forward_list::before_begin() is an inbuilt function in C++ STL which is declared in <forward_list> header file. before_begin() returns the iterator which is pointing to the element before the first element in the forward_list container.

Syntax

forwardlist_container.before_begin();

This function accepts no parameter.

Return Value

This function returns a iterator to the position before the beginning of the sequence.

Example

/* In the below code we are creating a forward list and then using the before_begin() function we will point to the first element in a forward list and after that we will try to insert a new element in front of the forward list using insert_after() function. Now, we will notice the changes in the output. */

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   //creating and initializing forward list
   forward_list<int> forwardList = { 3, 6, 1, 2, 4 };
   //calling before_begin function
   auto i = forwardList.before_begin();
   //inserting element before forward list
   forwardList.insert_after(i, 7);
   cout<< "Element of the forward list are:" << endl;
   for (auto j = forwardList.begin(); j != forwardList.end(); ++j)
      cout << *j << " ";
   return 0;
}

Output

If we run the above code it will generate the following output

Element of the forward list are:
7 3 6 1 2 4

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   forward_list<int> forwardList = {2, 23, 12, 11};
   forwardList.insert_after(forwardList.before_begin(), 19 );
   cout << "Elements in the forward lists are : ";
   for (auto j = forwardList.begin(); j != forwardList.end(); ++j)
      cout << *j << " ";
   return 0;
}

Output

If we run the above code it will generate the following output

Elements in the forward lists are : 19 2 23 12 11

Updated on: 02-Mar-2020

169 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements