views:

968

answers:

3

I've got a node struct

struct Node{CString text, int id;};

in a sorted vector.

I'm wondering if there's a function in algorithm that will do a binary search of the vector and find an element.

+4  A: 

Yes, there's a function called "binary_search" std::binary_search

You give it first, last and a value or a predicate.

See here for a sample

Combine that with Martin York's operator== and you should be OK (alternatively you can write a predicate functor

Binary Worrier
Actually for binary search, you need an operator<, not operator==
David Norman
Johannes Schaub - litb
Also note it does not find the element.It just test for existance.
Martin York
huh that's weird. why does it do that?
Johannes Schaub - litb
might be there multiple times. You can use lower_bound and upper_bound to find where.
tgamblin
oh i see. thanks
Johannes Schaub - litb
+18  A: 

std::binary_search() will tell you if a value exists in the container.

std::lower_bound()/std::upper_bound() will return an iterator to the first/last occurrence of a value.

Your objects need to implement operator< for these algorithms to work.

Ferruccio
or you need to use the other overload for `binary_search` and provide a comparator at the 4th parameter. This needs to be the same comparator you used to sort with.
KitsuneYMG
+1  A: 

Rather than a sorted vector<Node>
Why not use a map. This is a sorted container. So any search done on this via std::find() automatically has the same properties as a binary search.

Martin York
If your data is stable (no ongoing additions/deletions), it is more memory efficient to use the vector. If you need to interact with other parts of the system that expect a vector. Or you need to access the data by index. Or the data is accessed in a tight loop, where memory locality is important.
KeithB
"A sorted vector lets you iterate through the contents in order.": So does a map. (for (std::map<int>::iterator i = map.begin(); i != map.end(); ++i) ...)
Max Lybbert
a map also does't deal as smoothly with multiple instances of the key.
baash05
It lets you iterate in order of key. A closer analogy to a sorted vector is std::multiset.
Steve Jessop