In C++11 and later, std::list::cend() returns a const iterator that points one place after the last element of a std::list. Like end(), it is only a stop sign and not a real element.
It is the partner of cbegin() for loops and algorithms that only read the list. 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 cend with empty brackets. Compare iterators with it, but do not dereference it.
C++
for (auto it = l.cbegin(); it != l.cend(); ++it) { }
int n = std::count_if(l.cbegin(), l.cend(), pred);
int last = *std::prev(l.cend());
Call
What it does
l.cend()
Returns a const_iterator to the position after the last element.
cbegin() and cend() always come as a pair. Mixing cbegin() with end() also compiles, but the pair is easier to read.
Library declarations
C++
const_iterator cend() const noexcept; // since C++11
Parameters
Parameter
Description
None
cend() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
const_iterator
A read-only iterator to the position after the last element. It must not be dereferenced.
C++ Examples
Example 1 — cend() with std::prev()
Step one place back from cend() to read the last element without being able to change it.
C++
#include <iostream>
#include <iterator>
#include <list>
#include <string>
int main() {
std::list<std::string> l = {"red", "green", "blue"};
auto last = std::prev(l.cend());
std::cout << "last: " << *last << '\n';
return 0;
}
Output
last: blue
How It Works
l.cend() is a read-only iterator after the last node, so it cannot be dereferenced.
std::prev() moves it one step back, to the node that holds "blue". A list can do this quickly because every node knows its previous node.
*last reads the text. Writing *last = "x" would not compile, because the iterator is const.
Example 2 — cend() with std::count_if()
Count how many elements pass a test, using only read-only iterators.