In C++11 and later, std::list::crend() returns a const reverse iterator that stands one place before the first element of a std::list. It is the stop sign for a read-only backwards walk.
It is the partner of crbegin(). Like rend(), it does not refer to a real element. Include <list> to use it.
This is a member of std::list<T>, a doubly linked list. Every element lives in its own node with a link to the previous and the next node, so a list can insert and erase anywhere quickly once you hold an iterator. It has no access by index, so l[i] does not exist.
Syntax
Call crend with empty brackets and use it as the stop point of a read-only backwards walk.
C++
for (auto it = l.crbegin(); it != l.crend(); ++it) { }
auto r = std::find_if(l.crbegin(), l.crend(), pred);
bool none = (r == l.crend());
Call
What it does
l.crend()
Returns a const_reverse_iterator to the position before the first element.
crbegin() and crend() always come as a pair, like cbegin() and cend().
Library declarations
C++
const_reverse_iterator crend() const noexcept; // since C++11
Parameters
Parameter
Description
None
crend() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
const_reverse_iterator
A read-only reverse iterator to the position before the first element. It must not be dereferenced.
C++ Examples
Example 1 — crend() with std::find_if()
Search from the back for the last element that is bigger than 15.
C++
#include <algorithm>
#include <iostream>
#include <list>
int main() {
std::list<int> l = {10, 20, 30, 5};
auto r = std::find_if(l.crbegin(), l.crend(), [](int x) { return x > 15; });
if (r != l.crend()) {
std::cout << "last big one: " << *r << '\n';
}
return 0;
}
Output
last big one: 30
How It Works
The search starts at crbegin(), the node with 5. It is not bigger than 15, so the search goes on.
The next element from the back is 30. The test passes, so find_if() stops and returns an iterator to it.
If nothing had passed, the result would be crend(). Here r != l.crend() is true, so *r is safe to read.
Example 2 — crend() with std::distance()
The distance between crbegin() and crend() is the number of elements.