list end() function in C++ STL


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

What is a 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 list::end()?

list::end() is an inbuilt function in C++ STL which is declared in <list> header file. end() returns the iterator which is referred to the element next to the end position in the list container. This function doesn’t point to any element in the container.

This function is mostly used with list::begin() to give the range of a particular list container.

Syntax

list_container.end();

This function accepts no parameter.

Return Value

This function returns the past to the end element of a list container.

Example

/* In the below code we are using the function end() to traverse the elements present in a list using the function given. */

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   //create a list
   list<int> myList;
   //insert elements to List suing push_back() function
   myList.push_back(67);
   myList.push_back(12);
   myList.push_back(32);
   myList.push_back(780);
   myList.push_back(78);
   cout<<"elements in the list are :\n";
   for (auto j = myList.begin(); j!= myList.end(); j++){
      cout << *j << " ";
   }
   return 0;
}

Example

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

Elements in the list are:
67 12 32 780 78

Example

/* In the below code we are using header file to access the elements present in a list using the end() function. */

 Live Demo

#include <iostream>
#include <list>
int main (){
   //creating array of elements
   int values[] = {67, 12, 32, 780, 78};
   //inserting values to the list
   std::list<int> myList (values,values+5);
   std::cout << "elements in the list are :\n";
   //accessing list elements using iterator returned by an end() function
   for (std::list<int>::iterator i = myList.begin() ; i != myList.end(); ++i)
      std::cout << ' ' << *i;
   return 0;
}

Output

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

Elements in the list are:
67 12 32 780 78

Updated on: 02-Mar-2020

557 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements