简体   繁体   中英

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 ?

Just wrap a std::vector<S>::iterator . All operators can be forwarded directly except operator* which of course has to return S::a

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM