C++ std::array::size

The std::array::size function returns the number of elements in the array. It is a simple and efficient way to determine the size of a std::array at compile time. Unlike traditional arrays, this method ensures type safety and avoids common errors like using the sizeof operator incorrectly.


Syntax of std::array::size

</>
Copy
constexpr size_type size() const noexcept;

Parameters

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

Return Value

Returns the number of elements in the array as a value of type size_type. This value is constant and determined at compile time.


Examples for std::array::size

Example 1: Determining the Size of a std::array

This example demonstrates how to use the size function to determine the number of elements in a std::array:

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

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

    std::cout << "The size of the array is: " << arr.size() << std::endl;

    return 0;
}

Explanation:

  1. Define a std::array: An array of integers is defined with 5 elements.
  2. Use size(): The size() function is called on the array to get the number of elements, which is 5 in this case.
  3. Output the size: The result is printed to the console.

Output:

The size of the array is: 5

Example 2: Using std::array::size in a Loop

This example demonstrates using size() in a loop to iterate through the elements of a std::array:

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

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

    std::cout << "Array elements: ";
    for (std::size_t i = 0; i < arr.size(); ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation:

  1. Define a std::array: An array of integers is defined and initialized with 5 elements.
  2. Use size() in a loop: The size() function is used as the condition in a for loop to ensure the iteration runs exactly size() times, preventing out-of-bounds access.
  3. Access and print elements: Each element is accessed using its index and printed to the console.

Output:

Array elements: 1 2 3 4 5

Exception Handling in std::array::size

The std::array::size function does not throw exceptions as it is marked noexcept. It guarantees safe and efficient access to the size of the array at compile time.