![](/img/trans.png)
[英]finding the min and max element in vector using std::min_element, std::max_element
[英]Using std::max_element on a vector<double>
我正在尝试使用std::min_element
和std::max_element
来返回双精度向量中的min和max元素。 我的编译器不喜欢我目前正在尝试使用它们,我不理解错误消息。 我当然可以编写自己的程序来查找最小值/最大值,但我想了解如何使用这些函数。
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char** argv) {
double cLower, cUpper;
vector<double> C;
// code to insert values in C not shown here
cLower = min_element(C.begin(), C.end());
cUpper = max_element(C.begin(), C.end());
return 0;
}
这是编译器错误:
../MIXD.cpp:84: error: cannot convert '__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >' to 'double' in assignment
../MIXD.cpp:85: error: cannot convert '__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >' to 'double' in assignment
有人请解释我做错了什么吗?
min_element
和max_element
返回迭代器,而不是值。 所以你需要*min_element...
和*max_element...
正如其他人所说, std::max_element()
和std::min_element()
返回迭代器 ,需要取消引用才能获得该值 。
返回迭代器(而不仅仅是值)的优点是它允许您使用最大(或最小)值确定容器中(第一个)元素的位置 。
例如(为简洁起见使用C ++ 11):
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};
auto biggest = std::max_element(std::begin(v), std::end(v));
std::cout << "Max element is " << *biggest
<< " at position " << std::distance(std::begin(v), biggest) << std::endl;
auto smallest = std::min_element(std::begin(v), std::end(v));
std::cout << "min element is " << *smallest
<< " at position " << std::distance(std::begin(v), smallest) << std::endl;
}
这会产生:
Max element is 5 at position 4
min element is 1 at position 0
对于大型数据集,使用上面注释中建议的std::minmax_element()
可能会更快,但可能会产生稍微不同的结果。 上面我的示例的值将是相同的,但“max”元素的位置将是9
因为......
如果多个元素等效于最大元素,则返回最后一个元素的迭代器。
min / max_element将迭代器返回到min / max元素,而不是min / max元素的值。 您必须取消引用迭代器才能获取值并将其分配给double。 那是:
cLower = *min_element(C.begin(), C.end());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.