C++ std::list::cbegin

The std::list::cbegin function returns a constant iterator pointing to the first element of the list. This function is used when the contents of the list should not be modified during traversal. If the list is empty, the returned iterator is equal to cend().


Syntax of std::list::cbegin

</>
Copy
const_iterator cbegin() const noexcept;

Parameters

The std::list::cbegin function does not take any parameters.

Return Value

Returns a constant iterator pointing to the first element of the list. If the list is empty, the returned iterator is equal to cend().

Exceptions

The std::list::cbegin function does not throw exceptions as it is marked noexcept. However, dereferencing the iterator returned by cbegin() when the list is empty results in undefined behavior. It is recommended to check if the list is empty before accessing elements.


Examples for std::list::cbegin

Example 1: Traversing a List Using std::list::cbegin

This example demonstrates how to use cbegin() to traverse a list without modifying its elements:

</>
Copy
#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:

  1. Define a list: A std::list named myList is initialized with elements {10, 20, 30, 40, 50}.
  2. Use constant iterators: The cbegin() function provides a constant iterator pointing to the first element, and cend() provides a constant iterator pointing to one past the last element.
  3. Traverse the list: The for loop iterates from cbegin() to cend(), accessing and printing each element using the dereference operator (*it).

Output:

List elements: 10 20 30 40 50

Example 2: Preventing Modifications Using std::list::cbegin

This example demonstrates how cbegin() ensures that elements cannot be modified during traversal:

</>
Copy
#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:

  1. Define a list: A std::list named myList is initialized with elements {1, 2, 3, 4, 5}.
  2. Get a constant iterator: The cbegin() function provides a constant iterator pointing to the first element of the list.
  3. Attempt modification: Attempting to modify the element using the constant iterator will cause a compilation error, ensuring that the list remains unchanged.
  4. Access the first element: The value of the first element is printed using the dereference operator (*it).

Output:

First element: 1