C++ Standard Library C++ STL Library

C++ set - cend() Function



The C++ set::cend function returns the constant iterator (const_iterator) pointing to the past-the-last element of the set container. The past-the-last element of the set is the theoretical element that follows the last element. It does not point to any element, and hence could not be dereferenced.

C++ cbegin cend

Note: A const_iterator is an iterator that points to constant value. The difference between iterator and const_iterator is that the const_iterator cannot be used to modify the contents it points to, even if the set element is not itself constant.

Note: Set is an ordered data container which implies all its elements are ordered all the time.

Syntax

const_iterator cend() const noexcept;

Parameters

No parameter is required.

Return Value

A const_iterator to the past-the-last element of the sequence container.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the set::cend function returns the const_iterator pointing to the past-the-last element of the set MySet.

#include <iostream>
#include <set>
using namespace std;
 
int main (){
  set<string> MySet{"Alpha","Coding","Skills"};
  set<string>::const_iterator cit;

  cit = MySet.cend();
  cit--;
  cout<<*cit<<" ";
  cit--;
  cout<<*cit<<" ";
  cit--;
  cout<<*cit<<" ";
  return 0;
}

The output of the above code will be:

Skills Coding Alpha

Example:

Lets see another example where the set called MySet contains integer values and set::cend function is used with set::cbegin function to specify a range including all elements of the set container. Please note that, Set is an ordered data container.

#include <iostream>
#include <set>
using namespace std;
 
int main (){
  set<int> MySet{55, 25, 128, 5, 72};
  set<int>::const_iterator cit;

  for(cit = MySet.cbegin(); cit != MySet.cend(); ++cit)
    cout<<*cit<<" ";

  return 0;
}

The output of the above code will be:

5 25 55 72 128 

❮ C++ <set> Library