Reference to inner index?
Suppose I have
vector<vector<int> > a;
which is indexed as
a[i][j] = stuff;
where i is "outer" and j is "inner"...
Then creating a reference to the "outer开发者_运维技巧" vector is easy:
vector<int>& b = a[x];
Is there a nice way to create a reference to the inner?
vector<int>& b = a[<don't know>][x];
Thanks.
Unfortunately, no, there's no direct way of creating a reference like that because the compiler is treating this like
a.operator[] (/* ... don't know ... */).operator[] (x);
This only makes sense if the first call to operator []
actually hands back a vector
.
However, what you can do is fake this behavior by introducing a new class that specifically handles the behavior. The idea is to have this class store the second index and provide an operator[]
function that, given the first index, looks up the real value in the vector
. Here's one example:
class IndexReverser { // Or, your favorite name
public:
IndexReverser(vector< vector<int> >& v, size_t index);
int& operator[] (size_t firstIndex);
private:
vector< vector<int> >& realVector;
const size_t secondIndex;
};
IndexReverser::IndexReverser(vector< vector<int> >&v,
size_t index) : realVector(v), secondIndex(index) {
// Handled in initialization list
}
int& IndexReverser::operator[] (size_t firstIndex) {
return realVector[firstIndex][secondIndex];
}
You could then write, for example, this:
IndexReverser ir(a, j);
ir[i] = 137;
You might need to provide a twin class to handle const
vectors, and probably would want to parameterize the entire structure on the type of the elements being stored. I'm not sure if this is what you're looking for, but it least shows that in principle you can get the behavior you want.
This line:
vector<int>& b = a[x];
is not a reference to the outer vector but rather one of the inner vectors. Also note that there are possible many inner vectors.
Here's how to get a reference to the outer vector (although in general it would be pointless):
vector<vector<int> > &outer = a;
Getting a reference to one of the inner vectors looks something like this:
vector<int> &inner = a[x];
精彩评论