Re: Test if std::vector<> contains a specific entry
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;
}
}
Works perfectly! Thanks a lot!
I have a list of C++ related books that I'm working through and STL is one of them. I think I'll put that one higher in the priority!
Note that if the data is sorted it can be searched more efficiently. For small amounts of data it is efficient to search sequentially but for a large amount of data it could be quite significantly better if the search is not sequential.
Bookmarks