Skip to main content

C++ STL

Min/Max Functions

Complete lesson for Min/Max Functions using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with C++ OOP and STL where relevant.

L1

Basics — Min/Max Functions

Section: C++ STL. C++ min/max — std::min, std::max, min_element, max_element, minmax, and Min vs Min_element.

What are min/max utilities?

  • The STL gives helpers to find the **smaller** or **larger** of values — or of a whole **range**.
  • Value helpers: min, max, minmax (in ).
  • Range helpers: min_element, max_element, minmax_element.
  • **Real-life:** pick the cheaper of two prices, or the top score in a list.
FunctionWorks onReturns
min(a,b)Two valuesThe smaller value
max(a,b)Two valuesThe larger value
minmax(a,b)Two valuespair {min, max}
min_element(f,l)Iterator rangeIterator to smallest
max_element(f,l)Iterator rangeIterator to largest
minmax_element(f,l)Iterator rangePair of iterators {min, max}

Why use them?

  • Clearer and less error-prone than hand-written ifs.
  • Work with any comparable type (int, string, custom with operator<).
  • Range versions integrate with iterators / containers.
  • One-pass minmax_element finds both extremes efficiently.

Differences between min and min_element

  • Same idea (find the smallest) — different inputs and return types.
Featuremin / maxmin_element / max_element
InputTwo values (or initializer_list)Iterator range [first, last)
Return typeA **value** (or const ref to argument)An **iterator** to the element
Use whenYou already have two (or few) valuesYou search inside a container/array
Empty rangeN/A for two-arg formReturns last (end)
Header
Examplemin(3, 7) → 3*min_element(v.begin(), v.end())
Index needed?NoYes — it - v.begin() (random-access)
Custom orderOptional comparatorOptional comparator

min and max for values

  • min(a, b) / max(a, b) compare with operator< by default.
  • Initializer-list overloads: min({3, 1, 4, 1}).
  • Prefer these over writing a < b ? a : b repeatedly.
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    cout << min(3, 7) << "\n";          // 3
    cout << max(3, 7) << "\n";          // 7
    cout << min({9, 2, 5, 2}) << "\n";  // 2
    cout << max({'a', 'z', 'm'}) << "\n";
    return 0;
}

minmax for two values

  • minmax(a, b) returns pair with {smaller, larger}.
  • One comparison path for both results.
#include <iostream>
#include <algorithm>
#include <utility>
using namespace std;

int main() {
    auto [lo, hi] = minmax(8, 3);
    cout << lo << " " << hi << "\n"; // 3 8
    return 0;
}

min_element and max_element

  • Scan a range; return an **iterator** to the extreme element.
  • Dereference to read the value: *min_element(...).
  • If the range is empty, returns last (do not dereference).
  • First occurrence wins if there are ties.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {4, 1, 9, 1, 7};
    auto mn = min_element(v.begin(), v.end());
    auto mx = max_element(v.begin(), v.end());
    cout << *mn << " at " << (mn - v.begin()) << "\n";
    cout << *mx << " at " << (mx - v.begin()) << "\n";
    return 0;
}

minmax_element — both in one pass

  • minmax_element returns pair {min_it, max_it}.
  • More efficient than calling min_element and max_element separately.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {4, 1, 9, 2};
    auto [mn, mx] = minmax_element(v.begin(), v.end());
    cout << *mn << " " << *mx << "\n"; // 1 9
    return 0;
}

Custom comparators

  • Pass a comparator for custom order (e.g. by absolute value, by string length).
  • Same idea as sort comparators — return whether left is “less” than right.
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;

int main() {
    vector<int> v = {-5, 2, -9, 4};
    auto it = max_element(v.begin(), v.end(),
        [](int a, int b) { return abs(a) < abs(b); });
    cout << *it << "\n"; // -9 (largest magnitude)
    return 0;
}

Key points to remember

  • min/max → values; *_element → iterators over a range.
  • Never dereference min_element result if the range was empty.
  • minmax_element finds both extremes in one pass.
  • Ties: the **first** minimum / maximum iterator is returned.
  • Header .
L2

Advanced — Min/Max Functions

Return type details

  • Two-arg min/max return a const reference to one of the arguments (lifetime tied to those args).
  • Initializer-list overloads return by **value**.
  • *_element always returns an iterator — convert to index with it - begin on random-access ranges.

clamp (related, C++17)

  • clamp(v, lo, hi) forces v into [lo, hi].
  • Handy sibling of min/max for bounded values.
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    cout << clamp(15, 0, 10) << "\n"; // 10
    cout << clamp(-3, 0, 10) << "\n"; // 0
    return 0;
}

Working with strings and pairs

  • min/max work on string (lexicographic).
  • On pair, comparison is lexicographic — useful for scored pairs.
#include <iostream>
#include <string>
#include <algorithm>
#include <utility>
using namespace std;

int main() {
    cout << min(string("bee"), string("be")) << "\n";
    cout << max(make_pair(1, 9), make_pair(1, 5)).second << "\n"; // 9
    return 0;
}

Stability of ties

  • If several elements equal the minimum, min_element points to the **first**.
  • Same for max_element — first maximum.

Design tips

  • Two values → min/max; whole container → *_element.
  • Need both extremes of a range → minmax_element.
  • Need index often → keep random-access container (vector).
  • For “top-K” repeatedly, consider priority_queue instead of rescanning.
L3

Tricky Interview Points

Q1) Difference between min and min_element?

Answer min compares values and returns a value; min_element scans a range and returns an iterator to the smallest element.

Q2) What does max_element return?

Answer An iterator to the largest element in [first, last), or last if the range is empty.

Q3) What if there are duplicate maxima?

Answer max_element returns the first occurrence of the maximum value.

Q4) What is minmax_element?

Answer Finds both the minimum and maximum iterators in one pass; returns pair<it_min, it_max>.

Q5) Header for these functions?

Answer <algorithm>

Q6) Can min take more than two arguments?

Answer Yes via initializer_list overload, e.g. min({1,5,2}).

Q7) How do you get the index of the maximum in a vector?

Answer auto it = max_element(v.begin(), v.end()); size_t i = it - v.begin();

Q8) How do custom comparators work with max_element?

Answer Pass a callable that defines “less”; max_element finds the last in that order (the greatest under <).

Q9) min vs clamp?

Answer min picks the smaller of two; clamp restricts a value to a closed [lo, hi] interval (C++17).

Q10) Does min modify its arguments?

Answer No — it returns which one is smaller without changing them.

Q11) Complexity of min_element?

Answer Linear in the size of the range — O(n) comparisons.

Q12) Why prefer minmax_element over min_element + max_element?

Answer It finds both extremes in roughly one pass instead of two full scans.

L4

Simple Programs

min and max of two values

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    cout << min(12, 5) << "\n";
    cout << max(12, 5) << "\n";
    return 0;
}

min with initializer_list

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    cout << min({8, 3, 5, 1, 9}) << "\n";
    cout << max({8, 3, 5, 1, 9}) << "\n";
    return 0;
}

min_element / max_element on vector

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {5, 2, 9, 2, 7};
    cout << *min_element(v.begin(), v.end()) << "\n";
    cout << *max_element(v.begin(), v.end()) << "\n";
    return 0;
}

Index of maximum

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {5, 2, 9, 2, 7};
    auto it = max_element(v.begin(), v.end());
    cout << "max=" << *it << " index=" << (it - v.begin()) << "\n";
    return 0;
}

minmax_element

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {5, 1, 8, 3};
    auto [mn, mx] = minmax_element(v.begin(), v.end());
    cout << *mn << " " << *mx << "\n";
    return 0;
}

Custom comparator — longest string

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main() {
    vector<string> w = {"fig", "banana", "kiwi"};
    auto it = max_element(w.begin(), w.end(),
        [](const string& a, const string& b) {
            return a.size() < b.size();
        });
    cout << *it << "\n"; // banana
    return 0;
}
L5

Problem Solving Tricks

  • min/max → values; *_element → iterators.
  • Header .
  • Empty range: *_element returns end — do not dereference.
  • Ties: first minimum / first maximum.
  • minmax_element = both extremes, one pass.
  • min({...}) works with initializer_list.
  • Index: it - v.begin() on vector.
  • Custom order via comparator lambda.
  • clamp(v, lo, hi) related helper (C++17).
  • Prefer minmax for two values when you need both.
  • Strings compare lexicographically with min/max.
  • Min vs Min_element table is a common interview ask.
L6

Practice Programs List

  1. Print min and max of two user-entered ints.
  2. Use min({...}) on five numbers.
  3. Find min_element and max_element in a vector; print values and indices.
  4. Use minmax_element and structured bindings.
  5. Find the longest string in a vector with a comparator.
  6. Demonstrate first-tie behaviour with duplicate minima.
  7. Write Min vs Min_element table in comments (8 rows).
  8. Clamp a list of scores to 0..100.
  9. Find max absolute value in a vector of ints.
  10. Compare two strings with min/max and explain.
  11. Return pair of min/max from a function using minmax.
  12. Explain complexity of scanning with min_element.