-
August 28th, 2003, 05:08 PM
#1
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
-
August 28th, 2003, 05:51 PM
#2
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;
}
}
Regards,
Paul McKenzie
-
August 28th, 2003, 07:56 PM
#3
Beautiful!
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!
Thanks
-
August 29th, 2003, 12:42 PM
#4
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.
-
August 30th, 2003, 06:00 AM
#5
To add to Sam's post, if your data is sorted, you can use the binary_search() algorithm function.
Regards,
Paul McKenzie
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|