如何在C ++ 17中使用std :: min_element? [英] How to use std::min_element in C++17?

查看:142
本文介绍了如何在C ++ 17中使用std :: min_element?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一小段代码可以使用 std打印该范围内的最小元素:: min_element . cppreference示例打印最小元素的索引,但是我想打印最小元素而不是索引号.

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?

推荐答案

如果您查看std::min_element声明:

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?

这篇关于如何在C ++ 17中使用std :: min_element?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆