uchar
uchar

Reputation: 2590

custom iterator for vector<struct>

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

Answers (2)

Luca Davanzo
Luca Davanzo

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:

  • *it: you access element pointer by iterator
  • **it: access element a thanks to the overloading

Upvotes: 1

MSalters
MSalters

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

Related Questions