Library contents

C++ std::min_element

In C++, std::min_element returns an iterator to the first smallest element in a range. For an empty range it returns the end iterator. Check that iterator before reading the value.

A simple example

std::min_element

  1. Start with 3, 1, 2
  2. Do this Keep the smallest
  3. Result 1
Compare the three values to find the one below the others.

Syntax

C++ syntax
*std::min_element(prices.begin(), prices.end())
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Find the cheapest item in a basket

A shopper compares the prices in a basket before paying. Work from the prices actually present in the list so a total or minimum reflects the same set of items as the receipt.

Result3
lesson.cpp
#include <algorithm>
#include <numeric>
#include <iostream>
#include <vector>

int main() {
    const std::vector<int> prices {8, 3, 12, 3};
    std::cout << (*std::min_element(prices.begin(), prices.end())) << "\n";
    return 0;
}
Output
3

The least expensive item costs three units. A tie still gives a single minimum price.

Advertisements

Count packs on the delivery slip

A loading desk receives four item counts in sequence. The supervisor needs to flag the smallest recorded count for review. Which count should the report show?

Given6 · 2 · 6 · 0
Worked result0

Review print quantities

A print room records four job quantities, including a cancelled job. The supervisor needs to flag the smallest recorded count for review. Which count should the report show?

Given3 · 0 · 8 · 3
Worked result0

What to watch for

Handle an empty basket before requesting a minimum. Empty-input behaviour varies by language.

Documentation for std::min_element