-1

Given:

class example
{
    public:
        std::vector<std::vector<int>> a;
        int b;
}

func()
{
    example e;
    ... // populate e

I could then use examples members like so.

    int n = e.b;
    int n2 = e.a[2][3];

However, could I alternatively override the [ ] operator such that.

    int n = e.b;
    int n2 = e[2][3];
}

?

edit: Sorry, the example is now fixed.

alan2here
  • 3,223
  • 6
  • 37
  • 62

2 Answers2

4

What you could do is overload the access operator and delegate it to the vector:

class example
{
    public:
        std::vector<std::vector<int>> a;
        int b;

        const std::vector<int>& operator[](std::size_t i) const
        {
            return a[i];
        }
        std::vector<int>& operator[](std::size_t i)
        {
            return a[i];
        }
};

The first [] will then return a reference to a's respective element, on which the second [] will be used.

Christian Rau
  • 45,360
  • 10
  • 108
  • 185
2

One naive solution would be to define your own operator[]:

class example
{
    std::vector<std::vector<int>> v;
public:
    std::vector<int> const & operator[](std::size_t i) const { return v[i]; }
    std::vector<int>       & operator[](std::size_t i)       { return v[i]; }

    // ...
};

Now if you have example e;, then e[1] is a vector of ints, etc.

It looks like you want to write some matrix class, though. For that, it's more efficient to have just a single vector and access it in strides:

class Matrix
{
    std::size_t cols;
    std::size_t rows;
    std::vector<int> v;

public:
    explicit Matrix(std::size_t r, std::size_t c) : cols(c), rows(r), v(r*c) { }

    int operator()(std::size_t i, std::size_t j) const { return v[i * cols + j]; }
    int & operator()(std::size_t i, std::size_t j) { return v[i * cols + j]; }
};

Now you can say: Matrix m(4, 7); m(1, 3) = 8;. You have to use the round-bracket operator for that, since the square-bracket operator must always take exactly one argument and thus isn't suitable here.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084