0

I know that for a simple 2d matrix like:

class Matrix{
  vector<vector<int>> data;
};

In order to support operation like Matrix[][], you just need to overload operator[] which returns the corresponding row vector like:

vector<int>& operator[](int row){return data[row]};

My question is how to implement the subscript operator if I need to perform some transformation on the col. Say for i th row, the size of that row is 10.

I want to return the actual data when j is less than 5 but some other value say i+j when j is greater than 5.

Is there a way to achieve this? Thanks!

2
  • You might return a proxy. Commented Apr 22, 2018 at 8:08
  • @Jarod42 Can you elaborate? Commented Apr 22, 2018 at 8:16

1 Answer 1

3

You might return proxy, something like:

class Proxy {
public:
    Proxy(std::vector<std::vector<int>>* data, std::size_t i) : data(data), i(i) {}

    int& operator[](std::size_t j) {
         if (j < 5) { return (*data)[i][j]; }
         else { return i + j; }
    }
private:
    std::vector<std::vector<int>>* data;
    std::size_t i;
};

class Matrix{
public:
    Proxy operator[](std::size_t i) { return {&data, i}; }
private:
    std::vector<std::vector<int>> data;
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.