Use Multidimensional Subscript Operator in C++23

Use Multidimensional Subscript Operator in C++23

Accessing elements in multidimensional data structures has traditionally required overloading operator() with as many parameters as there are dimensions or implementing dedicated accessor functions such as at(row, column). While these approaches work, they often result verbose syntax and reduce code readability.

For many years, operator[] was restricted to a single parameter, preventing true multidimensional indexing using the subscript operator. Since C++23, we can use the multidimensional subscript operator, allowing operator[] to accept multiple indices directly. This feature enables cleaner syntax when working with matrix-like structures and improves code clarity by expressing intent more naturally.

The following example demonstrates a simple matrix type that leverages the multidimensional subscript operator:

#include <iostream>
#include <vector>

class Matrix {
    std::vector<int> data;
    size_t rows;
    size_t cols;

public:
    Matrix(size_t r, size_t c)
        : data(r * c), rows(r), cols(c) {
    }

    int &operator[](size_t r, size_t c) {
        return data[r * cols + c];
    }
};

int main() {
    Matrix m(2, 3);
    m[1, 2] = 42;
    std::cout << m[1, 2] << std::endl;

    return 0;
}

In this code, elements are stored in a contiguous std::vector, and the multidimensional operator[] converts a row-column pair into a linear index. This approach provides intuitive access while maintaining efficient storage and aligns the syntax more closely with built-in arrays.

Leave a Comment

Cancel reply

Your email address will not be published.