Open In App

Vector crend() in C++ STL

Last Updated : 27 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, the vector crend() is a built-in method used to obtain a constant reverse iterator pointing to the theoretical element just before the first element of the vector. It is used to mark the reverse end of the vector.

Let’s take a look at an example:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 3, 5, 2, 4};

    // Print vector in reverse order
    for (auto it = v.crbegin(); it != v.crend(); ++it)
        cout << *it << " ";
    return 0;
}

Output
4 2 5 3 1 

This article covers the syntax, usage, and common examples of the vector crend() method in C++:

Syntax of vector crend()

The vector crend() is a member method of the std::vector class defined inside the <vector> header file.

v.crend();

Parameters:

  • This method does not take any parameters.

Return Value:

  • Returns a constant reverse iterator pointing to the element just before the first element of the vector.

Supported Iterator Operations

The vector crend() function returns a constant reverse iterator of type vector::const_reverse_iterator. Since it is a reverse random access iterator, it supports reverse traversal and arithmetic operations such as incrementing, decrementing, and adding/subtracting integers, subtraction of another iterator of same container, comparison.

However, as it is a constant iterator, you cannot modify the elements it points to. Doing so results in a compilation error.

Examples of vector crend()

This method is typically used with vector crbegin() to iterate over the vector in reverse without modifying its elements. The below example shows some use cases of vector crend():

Reverse Iterate Over a Vector

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 3, 5, 2, 4};

    // Reverse iterate using crbegin() and crend()
    for (auto it = v.crbegin(); it != v.crend(); ++it)
        cout << *it << " ";

    return 0;
}

Output
4 2 5 3 1 

Find the Largest Element Using Reverse Iterators

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 3, 5, 2, 4};

    // Find the largest element using reverse iterators
    int m = *max_element(v.crbegin(), v.crend());

    cout << m;
    return 0;
}

Output
5

Next Article
Article Tags :
Practice Tags :

Similar Reads