Open In App

Vector crbegin() in C++ STL

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

In C++, the vector crbegin() is a built-in method used to obtain a constant reverse iterator pointing to the last element of the vector. It is used to mark the starting point of reverse iteration over the vector without modifying its elements.

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};

    // Access the last elemement (reverse beginning)
  	cout << *v.crbegin();
  
    return 0;
}

Output
4

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

Syntax of Vector crbegin()

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

v.crbegin();

Parameters:

  • This method does not take any parameters.

Return Value:

  • Returns a constant reverse iterator pointing to the last element of the vector.

Supported Iterator Operations

The vector crbegin() function returns a constant reverse iterator of type vector::const_reverse_iterator. Being a reverse random access iterator, it supports reverse traversal and arithmetic operations such as:

  • Incrementing (++)
  • Decrementing (--)
  • Adding/Subtracting integers
  • Subtraction of another iterator of the same container
  • Comparison of iterators
  • Dereference

As a constant iterator, it cannot modify the elements it points to. Attempting to modify elements results in a compilation error.

Examples of Vector crbegin()

This method is typically used with vector crend() to iterate over the vector in reverse without modifying its elements. Below are some examples:

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 

Next Article
Practice Tags :

Similar Reads