Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there are no overloads of find/lower_bound for std::map and no overload of sort for std::list?

I know that you should never use std::find(some_map.begin(), some_map.end()) or std::lower_bound, because it will take linear time instead of logarithmic provided by some_map.lower_bound. Similar thing happens with std::list: there is std::list::sort function for sorting, but you're unable to call std::sort(some_list.begin(), some_list.end()), because iterators are not random-access.

However, std::swap, for instance, has overloads for standard containers, so that call of swap(some_map, other_map) takes O(1), not O(n). Why doesn't C++ standard give us specialized versions of lower_bound and find for maps and sets? Is there are deep reason?

like image 892
yeputons Avatar asked Mar 07 '14 20:03

yeputons


People also ask

What does Lower_bound return if not found?

lower_bound in c++ stl returns an iterator even when the element is not present.

Does lower bound work on array?

The lower_bound() and upper_bound() functions, by default works on non-decreasing array. The lower_bound() function finds iterator of first element that does not compare less to given element.

What does lower bound return?

The lower_bound() method in C++ is used to return an iterator pointing to the first element in the range [first, last) which has a value not less than val. This means that the function returns an iterator pointing to the next smallest number just greater than or equal to that number.


2 Answers

I don't think there's any deep reason, but it's more philosophical than anything. The free function forms of standard algorithms, including the ones you mention, take iterator pairs indicating the range over which they'll traverse. There's no way for the algorithm to determine the type of the underlying container from these iterators.

Providing specializations, or overloads, would be a departure from this model since you'd have to pass the container itself to the algorithm.

swap is different because it takes instances of the types involved as arguments, and not just iterators.

like image 123
Praetorian Avatar answered Sep 23 '22 05:09

Praetorian


The rule followed by the STL is that the free-function algorithms operate on iterators and are generic, not caring about the type of range the iterators belong to (other than the iterator category). If a particular container type can implement an operation more efficiently than using std::algo(cont.begin(), cont.end()) then that operation is provided as a member function of the container and called as cont.algo().

So you have std::map<>::lower_bound() and std::map<>::find() and std::list<>::sort().

like image 23
Jonathan Wakely Avatar answered Sep 22 '22 05:09

Jonathan Wakely