C++ .cend()
.cend() is a member function of standard C++ containers (such as arrays, vectors, and sets) that returns a constant iterator pointing just past the last element of the container. The “c” in .cend() stands for “const”, indicating that the iterator cannot modify the elements it accesses. This function is commonly used for read-only traversal and is typically employed in range checks or for loops to define the end boundary of the container.
Syntax
array.cend();
Parameters:
This function does not take any parameters.
Return value:
Returns a constant iterator pointing just past the last element of the container.
Example: Using .cend() to Access the Last Element
This example prints the last element of the array by using .cend() and moving one step backward:
#include <iostream>#include <array>int main() {std::array<int, 2> array = {1, 2};// Get constant iterator just past the last elementauto it = array.cend();// Move one step back to point to the last elementstd::cout << *(std::prev(it)) << "\n";return 0;}
The output of this code will be:
2
Codebyte Example: Using .cend() to Print an Array
This codebyte creates an array and uses .cbegin() and .cend() to print all of its elements:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours