Last Updated : 27 Nov, 2024
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;
}
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:
Return Value:
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;
}
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;
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4