-2

I have small piece of code to print smallest element in the range using std::min_element. cppreference example print the index of smallest element, but i want to print smallest element instead of index number.

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v{3, 1, 4, 1, -5, 9};
    std::cout << std::min_element(std::begin(v), std::end(v));
}

But, I got following an error:

main.cpp: In function 'int main()':
main.cpp:8:15: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and '__gnu_cxx::__normal_iterator<int*, std::vector<int> >')
     std::cout << std::min_element(std::begin(v), std::end(v));

So, What's the wrong with my code?

msc
  • 33,420
  • 29
  • 119
  • 214

1 Answers1

12

If you look at the std::min_element declaration:

template <class ForwardIterator>
  ForwardIterator min_element ( ForwardIterator first, ForwardIterator last );

you see that it returns an iterator. So you have to dereference it to access the actual value:

std::cout << *std::min_element(std::begin(v), std::end(v));

The rationale of that is obvious: what if you want to do anything other than printing the value, such as deleting it?

rodrigo
  • 94,151
  • 12
  • 143
  • 190