Open In App

cend() Function in C++

Last Updated : 27 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Cend() is the function defined in C++ STL. This function produces a constant random access iterator that identifies the deque’s past-the-end element. If the container is empty then cend() function returns the same as cbegin() function. This member function’s iterator can only be used to iterate containers; it cannot be used to change the content of the object it is pointing at. 

Syntax:

const_iterator cend() const noexcept;

A const_iterator is an iterator that points to constant content.

Example 1: Below is the C program to use cend() function in deque to print elements in reverse order:

C++




// C++ code demonstrating the use 
// of cend() function in deque
// to print elements in reverse
// order.
#include <iostream>
#include <deque>
using namespace std;
  
// Driver code
int main() 
{
  // Initialising the deque
  deque<int> d = {1, 2, 3, 4, 5};
    
  cout << "Elements of deque in reverse order: " << 
           endl;
  for (auto it = d.cend() - 1; 
            it >= d.cbegin(); --it)
    cout << *it << " ";
    
  cout << endl;
  return 0;
}


Output

Elements of deque in reverse order: 
5 4 3 2 1 
  • Time Complexity: O(n) where n is the number of elements in the deque.
  • Auxiliary Space: O(1)

Example 2: Below is the C program to use cend() function in deque to print elements of deque:

C++




// C++ code demonstrating the use 
// of cend() function in deque
// to print elements of deque
#include <iostream>
#include <deque>
using namespace std;
  
// Driver code
int main() 
{
  // Initialising the deque
  deque<string> d = {"geeks","for","geeks"};
    
  auto itr = d.cbegin();
  
  // Printing the deque with 
  // help of cend() function
  while(itr != d.cend())  
  {  
    cout << *itr;  
    cout << " ";  
    ++itr;  
  }   
  return 0;
}


Output

geeks for geeks 
  • Time Complexity: O(n) where n is the number of elements in the deque.
  • Auxiliary Space: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads