C++20 sections · 1024 units
Open in Course

min_element and max_element

Locating min and max

I'll show you min_element(v.begin(), v.end()) to find the smallest value. This returns an iterator, so dereference it: *min_element(v.begin(), v.end()). You can get the index: min_element(v.begin(), v.end()) - v.begin().

Subtracting the begin iterator gives you the position. max_element() works identically for finding the largest value. Both run in O(n)O(n) time and work with custom comparators.