C++23: Multidimensional Subscript Operator

When you have a class representing multidimensional data, providing access to a specific element in this multidimensional space is often done by providing an operator() with as many parameters as there are dimensions. You had to resort to operator(), because operator[] only supported a single index.

That’s now history, as C++23 introduces the multidimensional subscript operator. Providing such an operator for your class is straightforward:

import std;

template <typename T>
class Matrix
{
public:
	Matrix(std::size_t rows, std::size_t cols)
		: m_rows{ rows }, m_cols{ cols }
	{
		m_data.resize(rows * cols);
	}

	T& operator[](std::size_t x, std::size_t y) { return m_data[x + y * m_cols]; }

private:
	std::size_t m_rows;
	std::size_t m_cols;
	std::vector<T> m_data;
};

The class can be tested as follows:

const std::size_t Rows{4};
const std::size_t Cols{4};
Matrix<int> m{ Rows, Cols };
std::size_t counter{ 0 };
for (std::size_t y{ 0 }; y < Rows; ++y)
{
	for (std::size_t x{ 0 }; x < Cols; ++x)
	{
		m[x, y] = ++counter;
	}
}

for (std::size_t y{ 0 }; y < Rows; ++y)
{
	for (std::size_t x{ 0 }; x < Cols; ++x)
	{
		std::print("{} ", m[x, y]);
	}
	std::println("");
}
Share

Leave a Comment

Name: (Required)

E-mail: (Required)

Website:

Comment: