list begin( ) and list end( ) in C++ STL

C++Server Side ProgrammingProgramming

Given is the task to show the functionality list begin( ) and list end( ) function in C++ in STL.

What is List in STL

List is a data structure that allows constant time insertion and deletion anywhere in sequence. Lists are implemented as doubly linked lists. Lists allow non-contiguous memory allocation. List perform better insertion extraction and moving of element in any position in container than array, vector and deque. In List the direct access to the element is slow and list is similar to forward_list, but forward list objects are single linked lists and they can only be iterated forwards.

What is begin( )

The list begin( ) is used to return an iterator pointing to the first element of the list.

Syntax

list_name.begin( )


What is end( )?

The list end( ) is used to return an iterator pointing to the last element of the list.

Syntax

list_name.end( )

Example

Output  List − 10 11 12 13 14

Output  List − 66 67 68 69 70

Approach can be followed

  • First we intialize list

  • Then we define begin( ) and end( ).

By using the above approach we can print the list using begin( ) and end( ) function.

Example

/ / C++ code to demonstrate the working of begin( ) and end( ) function in STL
#include <iostream.h>
#include<list.h>
Using namespace std;
int main ( ){
   List<int> list = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
   / / print the list
   cout<< “ Elements in List: “;
   for( auto x = list.begin( ); x != list.end( ); ++x)
      cout<> *x << “ “;
   return 0;
}

Output

IF WE RUN THE ABOVE CODE THEN IT WILL GENERATE THE FOLLOWING OUTPUT

Elements of List: 11 12 13 14 15 16 17 18 19 20

Example

/ / C++ code to demonstrate the working of list begin( ) and end( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
int main ( ){
   List list = { ‘D’, ‘E’, ‘S’, ‘I’, ‘G’, ‘N’ };
   / / print the list
   cout << “ Elements in List: “;
   for( auto x = list.begin( ); x != list.end( ); ++x)
      cout<< *x << “ “;
   return 0;
}

Output

IF WE RUN THE ABOVE CODE THEN IT WILL GENERATE THE FOLLOWING OUTPUT

Elements in List: D E S I G N
raja
Published on 26-Feb-2020 15:13:42
Advertisements