I have a vector<data>
(where data
is my own pet type) and I want to find its maximum value.
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
:
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. 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):
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
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 < ()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.