3

This is a general question about operator overloading in cpp.
Is there a way to overload operator[][] ?

I want to do this because I want to implement a Matrix class, where the user can do matrix[a][b] and access the element in that position.

My friend told me to represent the matrix like this:

vector<vector<T>>

And in the constructor I would initialize it like this:

Matrix(int row, int col): vector<vector<T>>(row, vector<T>(col)) {}

Can someone please explain what the constructor is doing?
And how would I implement accessing a specific element in my Matrix, so: matrix[a][b] = c

Edit: Seems like the operator[][] works fine, so i can do matrix[a][b] and access the element there.
Why is this?

Edit 2: Thanks for the suggestions to use () but according to the instructions, it needs to be able to work on this code: enter image description here

Toffe1369
  • 135
  • 1
  • 5
  • 1
    You do it by arranging for the result of `operator[]` to return a *proxy object*, which itself has an `operator[]` overload which yields the value. If you're smart about it the proxy object will not value copy the elements. Your friend's advice will get you off the ground but using `std::vector>` is not a natural representation as it models a jagged edge if you get my meaning (the rows can differ in length). Personally I use BLAS, and live with `(x, y)` for yielding a value. – Bathsheba Feb 18 '21 at 07:43
  • 1
    Some people also like to use `operator()` , because you can pass two parameters. Would be for example `Martix m; m(0, 0) = 4;`. Secondly: `vector>` is also rather inefficent, storing data in a 1D-vector is faster. – Lukas-T Feb 18 '21 at 07:46
  • Maybe create a template and then use `std::array, M>` instead of `vector` – Olaf Dietsche Feb 18 '21 at 07:50
  • Judging by your code your Matrix class inherits from vector. That is why the vector [] works on your class. So it seems you don't need to overload [] at all. – john Feb 18 '21 at 08:02
  • This code `Matrix(int row, int col): vector>(row, vector(col)) {}` creates vec tor is size `row` where each element of that vector is another vector of size `col`. A 2D vector in other words. – john Feb 18 '21 at 08:03
  • ok i understand, Thank you!! – Toffe1369 Feb 18 '21 at 09:14
  • There is no `operator[][]`. When you see `m[0][1]` there are **two** index operators involved. `m[0]` operates on `m` and returns something that has its own `operator[]`, and that's what the `[1]` is applied to. – Pete Becker Feb 18 '21 at 14:41
  • Incredible good question! – X0-user-0X Aug 19 '22 at 21:06

0 Answers0