tags:

views:

86

answers:

4

Hi,

If I have a vector of object vector, how can I check if A* myA is inside that vector?

A: 

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;
}
VoodooChild
A: 

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...
}
nhaa123
+5  A: 

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;
}
Clark Gaebel
`end` will need to be a `const_iterator`.
Mike Seymour
@Mike good find :)
Clark Gaebel
A: 

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.

deemoowoor