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.