forward_list::begin() and forward_list::end() in C++ STL


In this article we will be discussing the working, syntax and examples of forward_list::begin() and forward_list::end() functions 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::begin()?

forward_list::begin() is an inbuilt function in C++ STL which is declared in header file. begin() returns the iterator which is referred to the first element in the forward_list container. Mostly we use begin() and end() together to give the range of an forward_list container.

Syntax

forwardlist_container.begin();

This function accepts no parameter.

Return Value

This function returns a bidirectional iterator pointing to the first element of the container.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   //creating a forward list
   forward_list<int> forwardList = { 4, 1, 2, 7 };
   cout<<"Printing the elements of a forward List\n";
   //calling begin() to point to the first element
   for (auto i = forwardList.begin(); i != forwardList.end(); ++i)
      cout << ' ' << *i;
   return 0;
}

Output

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

Printing the elements of a forward List
4 1 2 7

What is forward_list::end()?

forward_list::end() is an inbuilt function in C++ STL which is declared in header file. end() returns the iterator which is referred to the last element in the forward_list container. Mostly we use begin() and end() together to give the range of an forward_list container.

Syntax

forwardlist_container.end();

This function accepts no parameter.

Return Value

This function returns a bidirectional iterator pointing to the first element of the container.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   //creating a forward list
   forward_list<int> forwardList = { 4, 1, 2, 7 };
   cout<<"Printing the elements of a forward List\n";
   //calling begin() to point to the first element
   for (auto i = forwardList.begin(); i != forwardList.end(); ++i)
      cout << ' ' << *i;
   return 0;
}

Output

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

Printing the elements of a forward List
4 1 2 7

Updated on: 02-Mar-2020

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements