Start learning free

LESSON 265 OF 667 · PAIRS, SORTING & BUILT-INS

Min, Max and Sum in C++

Lesson

TL ; DR:

*min_element(v.begin(), v.end()) gives the smallest value of a vector.

*max_element gives the largest value.

accumulate adds all the values up.


vector<int> prices = {4, 9, 2, 7};

cout << *min_element(prices.begin(), prices.end()) << endl;    // 2

cout << *max_element(prices.begin(), prices.end()) << endl;    // 9

int total = accumulate(prices.begin(), prices.end(), 0);

cout << total << endl;                                          // 22


Full lesson:

In Maximum Number In Array, a loop found the largest value. In Sum of Numbers, a loop added numbers up. These jobs come up all the time. The C++ library has them ready-made.

  • min_element(v.begin(), v.end()) finds the smallest value of the vector v.
  • max_element(v.begin(), v.end()) finds the largest value.
  • accumulate(v.begin(), v.end(), 0) adds all the values to a start value, 0.

begin() and end() mark the whole vector. min_element returns where the smallest value is, not the value. The * in front reads the value there.

The three come from the headers <algorithm> and <numeric>. This lesson already includes them.

The start value also sets the total's type. With 0 the total is an int. For doubles, start at 0.0, or the fractions get lost.

max(a, b) from Maximum Number In Array compares two values. max_element looks at a whole vector.

Watch out for an empty vector. There, min_element returns v.end(), a spot past the last value. Reading it with * is undefined behavior. The program may crash or print garbage. Check v.empty() first. accumulate on an empty vector gives its start value, 0.


Your task

minutes holds how many minutes you practiced coding on each day of a week.

Store the shortest day in shortest and the longest day in longest. Store the week's total in total.

Use the built-ins from this lesson. The code at the bottom prints all three.

Expected output:

shortest = 15
longest = 60
total = 235
STEP 1 OF 3
    Ctrl + Enter to check