C++ Container Classes<array>

The C++11 standard introduced<array>The header file provides a fixed-size array container, which offers better type safety and memory management characteristics compared to arrays in C.

std::arrayIt is a template class in the C++ standard library, defined in<array>In the header file.std::arrayThe template class provides a fixed-size array whose size is determined at compile time and cannot be changed dynamically.

Syntax

std::arrayThe basic syntax is as follows:

#include <array>

std::array<T, N> array_name;
  • Tis the type of elements in the array.
  • NIt is the size of the array and must be a non-negative integer.

Declaration and Initialization

<array>The size needs to be determined at compile time and cannot be changed dynamically. Usage example:

#include <iostream>
#include <array>

int main() {
    std::array<int, 5> arr = {1, 2, 3, 4, 5}; // 声明一个定长为5的int数组
    return 0;
}

Features

  • Type Safety:std::arrayEnforces type checking, avoiding the type safety issues of C language arrays.
  • Fixed size: The size of the array is determined at compile time and cannot be changed at runtime.
  • Contiguous memory:std::arrayThe elements are stored contiguously in memory, which allows efficient element access.
  • Standard Container:std::arrayprovidesstd::vectorSimilar interfaces, such assize(), at(), front(), back()etc.

Example

Below is an example usingstd::arrayA simple example, including the output results.

Example

#include <iostream>
#include <array>

int main() {
    // Create a std::array containing 5 integers
    std::array<int, 5> myArray = {1, 2, 3, 4, 5};

    // Use a range-based for loop to iterate through the array
    for (const auto& value : myArray) {
        std::cout << value << " ";
    }
    std::cout << std::endl;

    // Access array elements using index
    std::cout << "Element at index 2: " << myArray.at(2) << std::endl;

    // Get the size of the array
    std::cout << "Array size: " << myArray.size() << std::endl;

    // Modify array elements
    myArray[3] = 10;

    // Iterate through the array again to display the modified elements
    for (const auto& value : myArray) {
        std::cout << value << " ";
    }
    std::cout << std::endl;

    return 0;
}

Output:

1 2 3 4 5 
Element at index 2: 3
Array size: 5
1 2 3 10 5 

Common Member Functions

The following are<array>Some commonly used member functions in:

Function Description
at(size_t pos) Returns the element at the specified position, with bounds checking
operator[] Returns the element at the specified position, without bounds checking
front() Returns the first element of the array
back() Returns the last element of the array
data() Returns a pointer to the array data
size() Returns the array size (fixed and unchanged)
fill(const T& value) Sets all elements of the array to the specified value
swap(array& other) Swaps the contents of two arrays
begin() / end() Return the begin/end iterators of the array

Example

1. Basic Operations

Example

#include <iostream>
#include <array>

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

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

    // Get the first and last elements
    std::cout << "First element: " << arr.front() << std::endl;
    std::cout << "Last element: " << arr.back() << std::endl;

    return 0;
}

Using at and bounds checking

Example

#include <iostream>
#include <array>

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

    try {
        std::cout << arr.at(2) << std::endl;  // Normal output
        std::cout << arr.at(5) << std::endl;  // Out of range, throws an exception
    } catch (const std::out_of_range& e) {
        std::cout << "Exception: " << e.what() << std::endl;
    }

    return 0;
}

3. Using fill to fill elements

Example

#include <iostream>
#include <array>

int main() {
    std::array<int, 5> arr;
    arr.fill(100);  // Set all elements to 100

    std::cout << "Filled array: ";
    for (const auto& elem : arr) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    return 0;
}

4. Array Swapping

Example

#include <iostream>
#include <array>

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

    arr1.swap(arr2);

    std::cout << "Array 1: ";
    for (const auto& elem : arr1) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    std::cout << "Array 2: ";
    for (const auto& elem : arr2) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    return 0;
}

Comparison with other array types

Featuresstd::arrayC-Style Arraysstd::vector
SizeFixed at compile timeFixed at compile timeDynamically changeable
Bounds checkingat()Provides bounds checkingNoneat()Provides bounds checking
Memory ManagementStack allocationStack allocationHeap allocation
PerformanceEfficientEfficientLower (dynamically allocated)
interfaceSupports STL standard interfaceDoes not support STL standard interfaceSupports STL standard interface

std::arrayIt is a very useful container in the C++ standard library, providing fixed-size arrays with the advantages of type safety and memory management. Through the above examples, we can see how to create, access, and modifystd::arraythe elements. For scenarios that require fixed-size arrays,std::arrayis a very good choice.

other extensions