I have a vector<data>
(where data
is my own pet type) and I want to find its maximum value.
我有一个向量 (其中data是我自己的pet类型),我想找到它的最大值。
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
:
标准的std::max函数在c++ 11中似乎可以处理一个对象集合,但是它希望初始化列表作为它的第一个参数,而不是像向量这样的集合:
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 ?
我怎么解决这个问题?
2 个解决方案
#1
18
The std::max
overloads are only for small sets known at compile time. What you need is std::max_element
(which is even pre-11). This returns an iterator to the maximum element of a collection (or any iterator range):
最大过载仅适用于编译时已知的小集。您需要的是std::max_element(甚至是pre-11)。这将返回一个迭代器到集合的最大元素(或任何迭代器范围):
auto max_iter = std::max_element(vd.begin(), vd.end());
// use *max_iter as maximum value (if vd wasn't empty, of course)
#2
1
Probably with lambda more flexibly
可能更灵活。
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”的compare操作符::operator < ()
#1
18
The std::max
overloads are only for small sets known at compile time. What you need is std::max_element
(which is even pre-11). This returns an iterator to the maximum element of a collection (or any iterator range):
最大过载仅适用于编译时已知的小集。您需要的是std::max_element(甚至是pre-11)。这将返回一个迭代器到集合的最大元素(或任何迭代器范围):
auto max_iter = std::max_element(vd.begin(), vd.end());
// use *max_iter as maximum value (if vd wasn't empty, of course)
#2
1
Probably with lambda more flexibly
可能更灵活。
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”的compare操作符::operator < ()