C++ Standard Library C++ STL Library

C++ <iterator> - crend() Function



The C++ <iterator> crend() function returns an iterator pointing to the reverse past-the-last element in the sequence. The container's object is always treated as constant qualified and if the sequence is a standard container, the function always returns a const_reverse_iterator.

C++ crbegin crend

These function templates are defined in multiple headers which are: <iterator>, <array>, <deque>, <forward_list>, <list>, <map>, <regex>, <set>, <string>, <string_view>, <unordered_map>, <unordered_set> and <vector>.

Syntax

template <class Container>
  auto crend (const Container& cont)
    -> decltype (rend(cont));
template <class Container>
  constexpr auto crend (const Container& cont)
    -> decltype (rend(cont));

Parameters

cont Specify a container or view with a rend member function.

Return Value

Returns an iterator to the reverse past-the-last element of the sequence. The container's object is always treated as constant qualified and if the sequence is a standard container, the function always returns a const_reverse_iterator.

Example:

In the example below, the crend() function is used to iterate over an array to insert all elements of the array into a vector in reverse order.

#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
 
int main (){
  int arr[] = {10, 20, 30, 40, 50};
  vector<int> vec;

  //iterate over array to insert all elements of the
  //array into an empty vector in reverse order
  for(auto it = crbegin(arr); it != crend(arr); ++it)
    vec.push_back(*it);

  //print the content of the vector
  cout<<"vec contains: ";
  for(auto it = begin(vec); it != end(vec); ++it)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

vec contains: 50 40 30 20 10

❮ C++ <iterator> Library