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
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():
#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:
- Define an array: A
std::arrayof size 5 is defined and initialized with the elements{10, 20, 30, 40, 50}. - Use
cbegin()andcend(): Thecbegin()function provides a constant iterator pointing to the first element of the array, andcend()provides a constant iterator pointing to one past the last element. - Iterate through the array: A for loop is used to traverse the array, and the dereference operator
*itaccesses 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:
#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:
- Original array: The array
arris initialized with elements{1, 2, 3, 4, 5}. - Use
std::accumulate: Thestd::accumulatealgorithm calculates the sum of the elements in the range specified bycbegin()andcend(). - Output the result: The sum of the elements is stored in the variable
sumand 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.
