Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complexity of STL max_element

So according to the link here: http://www.cplusplus.com/reference/algorithm/max_element/ , the max_element function is O(n), apparently for all STL containers. Is this correct? Shouldn't it be O(log n) for a set (implemented as a binary tree)?

On a somewhat related note, I've always used cplusplus.com for questions which are easier to answer, but I would be curious what others think of the site.

like image 791
sas4740 Avatar asked Dec 10 '22 14:12

sas4740


1 Answers

It's linear because it touches every element.

It's pointless to even use it on a set or other ordered container using the same comparator because you can just use .rbegin() in constant time.

If you're not using the same comparison function there's no guarantee that the orders will coincide so, again, it has to touch every element and has to be at least linear.

Although algorithms may be specialized for different iterator categories there is no way to specialize them base on whether an iterator range is ordered.

Most algorithms work on unordered ranges (max_element included), a few require the ranges to be ordered (e.g. set_union, set_intersection) some require other properties for the range (e.g. push_heap, pop_heap).

like image 174
CB Bailey Avatar answered Dec 12 '22 04:12

CB Bailey