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

流过昼夜 提交于 2020-01-03 06:38:06

问题


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?


回答1:


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?



来源:https://stackoverflow.com/questions/46681144/how-to-use-stdmin-element-in-c17

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!