Possible Duplicate:
How to find an item in a std::vector?
This is what I'm looking for:
#include <vector> std::vector<int> foo() { // to create and return a vector return std::vector<int>(); } void bar() { if (foo().has(123)) { // it's not possible now, but how? // do something } }
In other words, I'm looking for a short and simple syntax to validate the existence of an element in a vector. And I don't want to introduce another temporary variable for this vector. Thanks!
So, to check if an element exist in vector or not, we can pass the start & end iterators of vector as initial two arguments and as the third argument pass the value that we need to check. If element exists in the vector, then it will return the iterator pointing to that element.
Yes, but sorting a vector modifies the original content.
Unsorted vector:
if (std::find(v.begin(), v.end(),value)!=v.end()) ...
Sorted vector:
if (std::binary_search(v.begin(), v.end(), value) ...
P.S. may need to include <algorithm>
header
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With