本文介绍了如何获得向量中的最大值或最小值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C++ 中获得向量中的最大值或最小值?

How can I get the maximum or minimum value in a vector in C++?

我假设它与数组或多或少相同是错误的吗?

And am I wrong in assuming it would be more or less the same with an array?

我需要一个迭代器,对吧?我用 max_element 尝试过,但我一直收到错误.

I need an iterator, right? I tried it with max_element, but I kept getting an error.

vector<int>::const_iterator it;
it = max_element(cloud.begin(), cloud.end());
error: request for member ‘begin’ in ‘cloud’, which is of non-class type ‘int [10]’

推荐答案

使用 C++11/C++0x 编译标志,你可以

Using C++11/C++0x compile flags, you can

auto it = max_element(std::begin(cloud), std::end(cloud)); // C++11

否则,请自行编写:

template <typename T, size_t N> const T* mybegin(const T (&a)[N]) { return a; }
template <typename T, size_t N> const T* myend  (const T (&a)[N]) { return a+N; }

http://ideone.com/aDkhW 现场观看:

See it live at http://ideone.com/aDkhW:

#include <iostream>
#include <algorithm>

template <typename T, size_t N> const T* mybegin(const T (&a)[N]) { return a; }
template <typename T, size_t N> const T* myend  (const T (&a)[N]) { return a+N; }

int main()
{
    const int cloud[] = { 1,2,3,4,-7,999,5,6 };

    std::cout << *std::max_element(mybegin(cloud), myend(cloud)) << '\n';
    std::cout << *std::min_element(mybegin(cloud), myend(cloud)) << '\n';
}

哦,还有 使用 std::minmax_element(...) 如果您同时需要两者:/

Oh, and use std::minmax_element(...) if you need both at once :/

这篇关于如何获得向量中的最大值或最小值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 09:59