[英]Impose a condition on std::max_element
Is there any way to make std::max_element
return the end
iterator if no element is grater than a certain value? 如果没有元素大于某个特定值,有什么方法可以使
std::max_element
返回end
迭代器?
Imagine I have this vector: 想象一下我有这个向量:
std::vector<int> vector{3, 6, 2, 5};
auto it = std::max_element(vector.begin(), vector.end());
How would you make it
point to vector.end()
if no element is greater than 7? 如果没有元素大于7,如何将
it
指向vector.end()
?
I don't see an algorithm to do this directly, but it's pretty trivial to tack it on after the fact: 我没有看到直接执行此操作的算法,但是在事实发生后再进行处理非常简单:
auto temp = std::max_element(v.begin(), v.end());
auto it = (temp ==v.end() || *temp > 7) ? temp : v.end();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.