C++ <array> operator[] operator

C++ container class <array>


Among all the ways to access array elements,operator[]is the most common and direct one, just like accessing a normal array.

operator[]is the subscript operator of container classes, used forreturning the element at the specified position, but it does not perform bounds checking. Its usage is exactly the same as a normal C array.

operator[]provides array-like random access capability, allowing you to quickly access elements at any position.

Word Definitions: operator[]is the subscript operator, and the square brackets are the symbol for array access.


Basic syntax and parameters

operator[]is a member function of the container class, just use it like an array.

Syntax format

reference operator[](size_type pos);
const_reference operator[](size_type pos) const;

Parameter description

  • Parameter: pos
    • Type:size_type(an unsigned integer type, usuallysize_t)
    • Description: The position (index) of the element to access. The index starts from 0, and the maximum valid index issize() - 1。

Function description

  • Return Value: returns the element at the specified position'sReference. If the container is a const container, a const reference is returned.
  • Effect: returns the element at the specified position. No bounds checking is performed; out-of-bounds access results in undefined behavior.
  • difference from at(): operator[]does not perform bounds checking, slightly faster;at()performs bounds checking and throws an exception when out of bounds.

Example

Let's thoroughly master it through a series of examples from simple to complex.operator[]Usage.

Example 1: Basic Usage - Accessing Elements

Example

#include <iostream>
#include <array>

int main() {
    // 1. Create an array and initialize it
    std::array<int, 5> numbers = {10, 20, 30, 40, 50};

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

    // 2. Use operator[] to access elements
    std::cout << "First element [0]: " << numbers[0] << std::endl;
    std::cout << "Second element [1]: " << numbers[1] << std::endl;
    std::cout << "Third element [2]: " << numbers[2] << std::endl;
    std::cout << "Last element [4]: " << numbers[4] << std::endl;

    // 3. Use a loop to access all elements
    std::cout << "All elements: ";
    for(size_t i = 0; i < numbers.size(); ++i) {
        std::cout << numbers[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

Expected output:

array的大小是: 5
第一个元素 [0]: 10
第二个元素 [1]: 20
第三个元素 [2]: 30
最后一个元素 [4]: 50
所有元素: 10 20 30 40 50

Code analysis:

  1. numbers[0]Return the first element10(index starts from 0).
  2. numbers[4]returns the last element50(becausesize()is 5, and the valid indices are 0-4).
  3. using loops andoperator[]can traverse all elements, and its usage is exactly the same as a C array.

Example 2: modifying element values

operator[]returns a reference, so it can be used to modify the value of the element.

Example

#include <iostream>
#include <array>

int main() {
    std::array<int, 3> numbers = {10, 20, 30};

    std::cout << "Before modification: ";
    for(size_t i = 0; i < numbers.size(); ++i) {
        std::cout << numbers[i] << " ";
    }
    std::cout << std::endl;

    // Use operator[] to get a reference and modify elements
    numbers[0] = 100;
    numbers[1] = 200;
    numbers[2] = 300;

    std::cout << "After modification: ";
    for(size_t i = 0; i < numbers.size(); ++i) {
        std::cout << numbers[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

Expected output:

修改前: 10 20 30
修改后: 100 200 300

Code analysis:

  • numbers[0] = 100;The value of the first element was modified through the reference.
  • This demonstratesoperator[]returns a modifiable lvalue reference.

Example 3: range-based for loop

You can use a range-based for loop to iterate over the array.

Example

#include <iostream>
#include <array>
#include <string>

int main() {
    std::array<std::string, 3> names = {"Alice", "Bob", "Charlie"};

    std::cout << "All elements: ";
    for(const auto& name : names) {
        std::cout << name << " ";
    }
    std::cout << std::endl;

    return 0;
}

Expected output:

所有元素: Alice Bob Charlie

Code analysis:

  • The range-based for loop is a concise way to access array elements.
  • andoperator[]compared to ..., the code is more concise and readable.

Example 4: calculating the dot product of vectors

Usageoperator[]Implement vector operations.

Example

#include <iostream>
#include <array>

// Calculate the dot product of two vectors
int dotProduct(const std::array<int, 3>& v1, const std::array<int, 3>& v2) {
    int result = 0;
    for(size_t i = 0; i < v1.size(); ++i) {
        result += v1[i] * v2[i];
    }
    return result;
}

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

    int result = dotProduct(v1, v2);

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

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

    std::cout << "Dot product: " << result << std::endl;
    // 1*4 + 2*5 + 3*6 = 4 + 10 + 18 = 32

    return 0;
}

Expected output:

向量 v1: 1 2 3
向量 v2: 4 5 6
点积: 32

Code analysis:

  • Usageoperator[]You can quickly access array elements in algorithms.
  • The dot product is calculated by multiplying the corresponding elements and then summing them.

C++ container class <array>

other extensions