开发者

How to iterate a list of vector

If I have a vector of object vector, how can I check if A* myA is inside that 开发者_C百科vector?


Try this...

#include <algorithm>

bool in_vector(const std::vector<A*>& vec, const A* myA)
{
    std::vector<A*>::const_iterator end = vec.end();
    return std::find(vec.begin(), end, myA) != end;
}


This might or might not work:

vector<int> v;
. . .
for (int i=0; i<v.size(); i++) {
  //---do a compare of v[i] with your object?  
  cout << v[i] << endl;
}


Perhaps something like this:

std::vector<A*> v;

for (std::vector<A*>::iterator it = v.begin(); it != v.end(); ++it) {
        // Do comparison with *it to your myA...
}


This is an expansion of wowus' answer for what I think is closer to what you want to do:

#include <algorithm>

// let's call it simply TVectorVectorA and TVectorA
typedef std::vector<std::vector<A*> > TVectorVectorA;
typedef TVectorVectorA::value_type TVectorA;

bool in_vector(const std::vector<std::vector<A*> >& vec, const A* myA)
{
    TVectorVectorA::const_iterator vend = vec.end();

    // iterate through all 'top-level' vectors
    for (TVectorVectorA::const_iterator it = vec.begin(); vend != it; ++it)
    {
           // check if the current TVector element contains myA
           if (std::find((*it).begin(), (*it).end(), myA) != end)
           { 
              return true;
           }
    }

    return false;
}

It's always nice to give a relevant code example (i.e. declaration of data types you're working with), when asking such questions. This way it's easier for others to understand what you want to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜