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.
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.
| Function | Works on | Returns |
|---|---|---|
min(a,b) | Two values | The smaller value |
max(a,b) | Two values | The larger value |
minmax(a,b) | Two values | pair {min, max} |
min_element(f,l) | Iterator range | Iterator to smallest |
max_element(f,l) | Iterator range | Iterator to largest |
minmax_element(f,l) | Iterator range | Pair of iterators {min, max} |
Why use them?
- Clearer and less error-prone than hand-written ifs.
- Work with any comparable type (
int,string, custom withoperator<). - Range versions integrate with iterators / containers.
- One-pass
minmax_elementfinds both extremes efficiently.
Differences between min and min_element
- Same idea (find the smallest) — different inputs and return types.
| Feature | min / max | min_element / max_element |
|---|---|---|
| Input | Two values (or initializer_list) | Iterator range [first, last) |
| Return type | A **value** (or const ref to argument) | An **iterator** to the element |
| Use when | You already have two (or few) values | You search inside a container/array |
| Empty range | N/A for two-arg form | Returns last (end) |
| Header | | |
| Example | min(3, 7) → 3 | *min_element(v.begin(), v.end()) |
| Index needed? | No | Yes — it - v.begin() (random-access) |
| Custom order | Optional comparator | Optional comparator |
min and max for values
min(a, b)/max(a, b)compare withoperator<by default.- Initializer-list overloads:
min({3, 1, 4, 1}). - Prefer these over writing
a < b ? a : brepeatedly.
#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)returnspairwith{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_elementreturnspair{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
sortcomparators — 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_elementresult if the range was empty. minmax_elementfinds both extremes in one pass.- Ties: the **first** minimum / maximum iterator is returned.
- Header
.
Advanced — Min/Max Functions
Return type details
- Two-arg
min/maxreturn a const reference to one of the arguments (lifetime tied to those args). - Initializer-list overloads return by **value**.
*_elementalways returns an iterator — convert to index withit - beginon random-access ranges.
clamp (related, C++17)
clamp(v, lo, hi)forcesvinto[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/maxwork onstring(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_elementpoints 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_queueinstead of rescanning.
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.
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;
} 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.
Practice Programs List
- Print min and max of two user-entered ints.
- Use min({...}) on five numbers.
- Find min_element and max_element in a vector; print values and indices.
- Use minmax_element and structured bindings.
- Find the longest string in a vector with a comparator.
- Demonstrate first-tie behaviour with duplicate minima.
- Write Min vs Min_element table in comments (8 rows).
- Clamp a list of scores to 0..100.
- Find max absolute value in a vector of ints.
- Compare two strings with min/max and explain.
- Return pair of min/max from a function using minmax.
- Explain complexity of scanning with min_element.