Test if std::vector<> contains a specific entry
How do I test to see whether or not a vector contains a specific entry? I've looked all over the MSDN doc on std::vector and I don't see anything.
For example:
std::vector<int> myVector;
myVector.push_back(10);
myVector.push_back(20);
myVector.push_back(30);
Aside from looping through the vector manually, what do I do to determine if the vector contains the value 20?
Thanks
Re: Test if std::vector<> contains a specific entry
Quote:
Originally posted by SteveS
How do I test to see whether or not a vector contains a specific entry? I've looked all over the MSDN doc on std::vector and I don't see anything.
That is because what you are looking for is an STL algorithm that works for many different containers, not just vector.
Use the std::find() algorithm. Note that std::find also works on plain old arrays too.
Code:
#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
std::vector<int> myVector;
myVector.push_back(10);
myVector.push_back(20);
myVector.push_back(30);
std::vector<int>::iterator it = std::find( myVector.begin(), myVector.end(), 20 );
if ( it != myVector.end() )
{
std::cout << "Found the element at position " <<
std::distance( myVector.begin(), it ) << std::endl;
std::cout << *it;
}
}
Regards,
Paul McKenzie