Reputation: 2590
Suppose I have a struct
like this :
struct S
{
int a;
string b;
//....
};
and I have a vector of this struct
:
vector<S> vect(100);
I want to have random_access iterator
that points to all of vect
int's member(a in this case)
How can I implement it ?
Upvotes: 1
Views: 435
Reputation: 21528
An elegant way could be the operator* overloading, direcly inside struct:
struct S {
int a;
string b;
inline int operator*() const {
return a;
}
};
In this way, when you iterate S elements in vector, you can access to 'a' in this easy way:
std::vector<S*> vect(100);
std::vector<S*>::iterator it = vect.begin();
for(; it != vect.end(); ++it) {
std::cout << **it;
}
with:
Upvotes: 1
Reputation: 179981
Just wrap a std::vector<S>::iterator
. All operators can be forwarded directly except operator*
which of course has to return S::a
Upvotes: 2