0

I want to overload a 2D vector's reference operator, [], with a pair of integers. For example, Consider a 2D vector of integers like this v = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

v[make_pair(1, 2)] Should return 6 at its at the 1st row and 2nd column (zero indexing).

Moltres
  • 600
  • 4
  • 21
  • Why? What is the actual problem that's supposed to solve? It's more to write than the standard `v[1][2]` (for a "2D" vector of vectors). – Some programmer dude Jan 15 '20 at 06:55
  • As for how to solve it: You can't. Not using standard `std::vector` anyway. The `operator[]` function must be a member function. Which means the only way to solve it is by making your own "2d vector" class. – Some programmer dude Jan 15 '20 at 06:56
  • Does this answer your question? [C++ \[\] array operator with multiple arguments?](https://stackoverflow.com/questions/1936399/c-array-operator-with-multiple-arguments) – Denis Sheremet Jan 15 '20 at 06:58
  • You need to make your own 2D vector class. As for overloading the operators for element access, rather than overloading [] you should overload the call operator () and provide as many argument as you want. Then, you can access it as v(1, 2) rather than v[{1,2}]. – Marius Bancila Jan 15 '20 at 06:59
  • @Someprogrammerdude I'm simulating a graph search, with a matrix of nodes and using pair for the current coordinates. So doing graph[curr.first][curr.second] looked ugly and hence I was wondering if I could just do graph[curr] – Moltres Jan 15 '20 at 07:16
  • 1
    You may define `operator[](const std::pair&)` with your matrix class. – Olaf Dietsche Jan 15 '20 at 07:18

0 Answers0