1

I wrote a struct to maintain a state of tic-tac-toe game.

struct Board{
    std::vector<std::vector<int>> board;

    Board() {
        board = std::vector<std::vector<int>> (3, std::vector<int> (3));
    }

    std::vector<int> & operator[](int id) { return board[id]; }
    int & operator[](std::pair<int, int> pos) { return board[pos.first][pos.second]; }
};

It works fine, and I can access the values within the struct in two ways:

Board position;
position[1][2] ++;
position[std::make_pair(0, 0)] --;

Then I realized that maybe it would be good to have some more general operator for two dimensional vector, to extract a value at some position given a pair of integers (something like this).

int & operator [] (std::vector<std::vector<int>> & vec, std::pair<int, int> & p) { return vec[p.first][p.second]; }

But then I was confronted with the following statement from the compiler:

stack.cpp:15:7: error: ‘int& operator[](std::vector<std::vector<int> >&, std::pair<int, int>&)’ must be a nonstatic member function
   15 | int & operator [] (std::vector<std::vector<int>> & vec, std::pair<int, int> & p) { return vec[p.first][p.second]; }
      |       ^~~~~~~~

Is there a way, to implement something with a functionality described above?

Yun
  • 3,056
  • 6
  • 9
  • 28
Fly_37
  • 312
  • 1
  • 12
  • 3
    As the error message says, `operator[]` has to be a non-static member function. So there’s no way to write it as a non-member. – Pete Becker Oct 17 '21 at 15:58
  • 1
    No, you cannot. You could add such operator for `Board` class, but I'd recommend against it. It's not a common way of overloading `operator[]` in C++, and uncommon operator overloads often create hard-to-read code. – Yksisarvinen Oct 17 '21 at 16:02
  • 3
    `position.at(0, 0)` looks more natural to me than your attempted syntax, and is straightforward to implement. – Igor Tandetnik Oct 17 '21 at 16:06
  • Also using pair for your coordinates isn't very readable. Just make a struct for a position with an x and a y member (or a letter and a number if your board is like a chessboard). And then you can write Board board; Position pos{1,1}; board.at(position); – Pepijn Kramer Oct 17 '21 at 16:19
  • I am asking because, though maybe less readable, this approach could speed up some implementations when it comes to competitive programming (as sometimes, I have to write two separate functions that are doing the same thing (for pair and just two integers)). – Fly_37 Oct 17 '21 at 16:55

0 Answers0