std::binary_search(), iterator to the found element and timecomplexity

A

Alex Vinokur

Hi,

std::binary_search() takes logarithmic time on (sorted) container, but
returns bool, not iterator to the found element.

std::find() returns iterator to the found element, but takes linear
time.

Is there any way to get iterator to the found element on sorted
container in logarithmic time?

Alex Vinokur
 
T

Thomas J. Gritzan

Alex said:
Hi,

std::binary_search() takes logarithmic time on (sorted) container, but
returns bool, not iterator to the found element.

std::find() returns iterator to the found element, but takes linear
time.

Is there any way to get iterator to the found element on sorted
container in logarithmic time?

std::lower_bound, std::upper_bound, std::equal_range
 
M

Maxim Yegorushkin

std::binary_search() takes logarithmic time on (sorted) container, but
returns bool, not iterator to the found element.

std::find() returns iterator to the found element, but takes linear
time.

Is there any way to get iterator to the found element on sorted
container in logarithmic time?

It is:

template<class Iter, class T>
Iter binary_search_iter(Iter begin, Iter end, T val)
{
Iter i = std::lower_bound(begin, end, val);
return i != end && *i == val
? i // found
: end // not found
;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top