tags:

views:

101

answers:

3

Possible Duplicate:
How to find an item in a std::vector?

Is there something in algorithm.h which allows you to check if a std:: container contains something? Or a way to make one ex:

if(a.x == b.x && a.y == b.y)
return true;

return false;

can this only be done with std::map since it uses keys?

Thanks

+3  A: 

See StackOverflow question 571394. You'll also need to ensure you've implemented a suitable operator==() for your object, if the default one isn't sufficient for a "deep" equality test.

NeilDurant
+5  A: 

Checking if v contains the element x:

if(std::find(v.begin(), v.end(), x) != v.end()) {
    /* v contains x */
} else {
    /* v does not contain x */
}

Checking if v contains elements (is non-empty):

if(!v.empty()){
    /* v is non-empty */
} else {
    /* v is empty */
}
You
Thanks You :)..
Milo
+2  A: 

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x)

runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - much more efficient with large numbers of elements.

std::set also guarantees all the added elements are unique, which saves you from having to do anything like 'if not contained then push_back()...`.

AshleysBrain