【问题标题】:How to use std::min_element in C++17?如何在 C++17 中使用 std::min_element?
【发布时间】:2018-03-22 17:04:02
【问题描述】:

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

#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));
}

但是,我收到以下错误:

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));

那么,我的代码有什么问题?

【问题讨论】:

  • 就像在 C++14 中使用它一样。

标签: c++ min c++17


【解决方案1】:

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

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

你看到它返回一个迭代器。所以你必须取消引用它才能访问实际值:

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

这样做的理由很明显:如果您想执行除打印值之外的任何操作(例如删除它)怎么办?

【讨论】:

    猜你喜欢
    • 2017-05-08
    • 2021-12-02
    • 1970-01-01
    • 2019-05-21
    • 2021-06-09
    • 1970-01-01
    • 2021-10-26
    • 2020-06-28
    • 1970-01-01
    相关资源
    最近更新 更多