C++ std::list::cend
The std::list::cend
function returns a constant iterator pointing to the position one past the last element of the list. It is primarily used with cbegin()
to safely iterate over the elements of the list without modifying them. The iterator returned by cend()
is not dereferenceable.
Syntax of std::list::cend
const_iterator cend() const noexcept;
Parameters
The std::list::cend
function does not take any parameters.
Return Value
Returns a constant iterator pointing to the position one past the last element of the list. This iterator is typically used as the end marker for a constant iteration.
Exceptions
The std::list::cend
function does not throw exceptions as it is marked noexcept
. However, dereferencing the iterator returned by cend()
results in undefined behavior, as it points to a position past the last element of the list.
Examples for std::list::cend
Example 1: Traversing a List Using std::list::cend
This example demonstrates how to use cbegin()
and cend()
to traverse a list without modifying its elements:
#include <iostream>
#include <list>
int main() {
std::list<int> myList = {10, 20, 30, 40, 50};
std::cout << "List elements: ";
for (auto it = myList.cbegin(); it != myList.cend(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
- Define a list: A
std::list
namedmyList
is initialized with elements{10, 20, 30, 40, 50}
. - Use constant iterators: The
cbegin()
function provides a constant iterator pointing to the first element, andcend()
provides a constant iterator pointing to one past the last element. - Traverse the list: The for loop iterates from
cbegin()
tocend()
, accessing and printing each element using the dereference operator (*it
).
Output:
List elements: 10 20 30 40 50
Example 2: Preventing Modifications with std::list::cend
This example demonstrates how cend()
ensures that elements cannot be modified during iteration:
#include <iostream>
#include <list>
int main() {
std::list<int> myList = {1, 2, 3, 4, 5};
auto it = myList.cbegin(); // Get a constant iterator
// *it = 10; // Uncommenting this line will cause a compilation error
std::cout << "First element: " << *it << std::endl;
return 0;
}
Explanation:
- Define a list: A
std::list
namedmyList
is initialized with elements{1, 2, 3, 4, 5}
. - Get a constant iterator: The
cbegin()
function provides a constant iterator pointing to the first element of the list. - Prevent modification: Attempting to modify the element using the constant iterator will cause a compilation error, ensuring the list remains unchanged.
- Access the first element: The value of the first element is printed using the dereference operator (
*it
).
Output:
First element: 1