[英]In c++11, how can I call std::max on a vector?
I have a vector<data>
(where data
is my own pet type) and I want to find its maximum value. 我有一个
vector<data>
(其中data
是我自己的宠物类型),我想找到它的最大值。
The standard std::max
function in C++11 appears to work on a collection of objects, but it wants an initializer list as its first argument, not a collection like vector
: C ++ 11中的标准
std::max
函数似乎适用于对象集合,但它需要初始化列表作为其第一个参数,而不是像vector
这样的集合:
vector<data> vd;
std::max(vd); // Compilation error
std::max({vd[0], vd[1], vd[2]}); // Works, but not ok since I don't vd.size() at compile time
How can I solve this ? 我怎么解决这个问题?
The std::max
overloads are only for small sets known at compile time. std::max
重载仅适用于编译时已知的小集。 What you need is std::max_element
(which is even pre-11). 你需要的是
std::max_element
(甚至是11之前的版本)。 This returns an iterator to the maximum element of a collection (or any iterator range): 这会将迭代器返回到集合的最大元素(或任何迭代器范围):
auto max_iter = std::max_element(vd.begin(), vd.end());
// use *max_iter as maximum value (if vd wasn't empty, of course)
Probably with lambda more flexibly 可能更灵活地使用lambda
vector<data> vd;
auto it = max_element(vd.cbegin(), vd.cend(), [](const data& left, const data& right)
{
return (left < right);
});
You just should implement operator of compare for your type "data" via data::operator < ()
你应该通过
data::operator < ()
为你的类型“data”实现compare的data::operator < ()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.