Michael
Michael

Reputation: 7829

C++ offers std::sort, but does it also offer something to search efficiently?

I have a vector of objects which implement operator< and operator==. C++ offers std::sort to sort that vector efficiently.

Is there also a function in std to efficiently search a vector repeatedly?

I will have many searches on that sorted vector, so std::find does not seem to be a good option, since it just walks through the iterator until it finds a match.

Upvotes: 0

Views: 88

Answers (2)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

Of course, there are.

For example, have a look at lower_bound and upper_bound functions.

Also binary_search may be useful.

All these functions work on the sorted input and have logarithmic complexity.

Upvotes: 4

woockashek
woockashek

Reputation: 1638

Try std::binary_search from #include <algorithm>

Upvotes: 2

Related Questions