'overload operator[][] for 2d vector [duplicate]
so currently i have to write a program in c++ where i have to create a class "CMyMatrix" and i wanted to know if its possible to overload the operator: "[][]"(i think technically they are 2 operators?) im using a 2d vector and would like the operator to work the same way as it works if you create a 2d array.
class CMyMatrix {
private:
std::vector<std::vector<double>> matrix;
int row_M = 0;
int column_N = 0;
public:
double& operator[][](int M, int N) { return something };
};
thank you for any help in advance.
Solution 1:[1]
This couldn't be done before C++23 since operator[]
must have exactly one argument.
With the adoption of the multidimensional subscript operator in C++23, now you can
#include <vector>
class CMyMatrix {
private:
std::vector<std::vector<double>> matrix;
int row_M = 0;
int column_N = 0;
public:
double& operator[](int M, int N) { return matrix[M][N]; };
};
int main() {
CMyMatrix m;
m[0, 1] = 0.42;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |