简体   繁体   中英

How to use std::min_element in C++17?

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM