C++ std::array::cbegin

The std::array::cbegin function returns a constant iterator pointing to the first element of the array. This iterator cannot modify the elements it points to, ensuring the array remains unchanged during iteration. It is commonly used when you need to iterate through a const array or when you want to guarantee read-only access.


Syntax of std::array::cbegin

</>
Copy
const_iterator cbegin() const noexcept;

Parameters

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

Return Value

Returns a constant iterator pointing to the first element of the array. If the array is empty, the returned iterator will be equal to std::array::cend.


Examples for std::array::cbegin

Example 1: Iterating Through an Array Using std::array::cbegin

This example demonstrates iterating through the elements of a std::array using cbegin() and cend():

</>
Copy
#include <iostream>
#include <array>

int main() {
    std::array<int, 5> arr = {10, 20, 30, 40, 50};

    std::cout << "Array elements: ";
    for (auto it = arr.cbegin(); it != arr.cend(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation:

  1. Define an array: A std::array of size 5 is defined and initialized with the elements {10, 20, 30, 40, 50}.
  2. Use cbegin() and cend(): The cbegin() function provides a constant iterator pointing to the first element of the array, and cend() provides a constant iterator pointing to one past the last element.
  3. Iterate through the array: A for loop is used to traverse the array, and the dereference operator *it accesses each element. The constant iterator ensures the elements cannot be modified.

Output:

Array elements: 10 20 30 40 50

Example 2: Using std::array::cbegin with a Standard Algorithm

This example demonstrates using std::array::cbegin with the std::accumulate algorithm to calculate the sum of the array’s elements:

</>
Copy
#include <iostream>
#include <array>
#include <numeric>

int main() {
    std::array<int, 5> arr = {1, 2, 3, 4, 5};

    int sum = std::accumulate(arr.cbegin(), arr.cend(), 0);

    std::cout << "Sum of array elements: " << sum << std::endl;

    return 0;
}

Explanation:

  1. Original array: The array arr is initialized with elements {1, 2, 3, 4, 5}.
  2. Use std::accumulate: The std::accumulate algorithm calculates the sum of the elements in the range specified by cbegin() and cend().
  3. Output the result: The sum of the elements is stored in the variable sum and printed to the console.

Output:

Sum of array elements: 15

Exception Handling in std::array::cbegin

The std::array::cbegin function does not throw exceptions as it is marked noexcept. This ensures safe access to a constant iterator pointing to the first element of the array.