How do I return the smallest member of an array?

How do I return the smallest member of an array using an abstract function?
Last edited on
if the array is plain C array, you would loop trough the array, and initialize temporal variable that would hold smallest member encountered during a loop.

in addition to array type it also depends on member type, you should mention with kind of array and data are you dealing with.
Last edited on
std::min_element()

It returns an iterator: just dereference it with *.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <algorithm>    // for min_element()
using namespace std;

int main()
{
   int          A[5] = {  7, -2,  3,  6, -1 };
   vector<int>  B    = { 30, 50, 20, 80, 20 };
   array<int,5> C    = { 11, 13,  9,  9, 12 };
   string       D[5] = { "Ford", "Toyota", "Vauxhall", "Nissan", "Volkswagen" };

   cout << "A: " << *min_element( A        , A + 5   ) << '\n';
   cout << "B: " << *min_element( B.begin(), B.end() ) << '\n';
   cout << "C: " << *min_element( C.begin(), C.end() ) << '\n';
   cout << "D: " << *min_element( D        , D + 5   ) << '\n';
}

Last edited on
Topic archived. No new replies allowed.