简体   繁体   English

在std :: max_element上施加条件

[英]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();

With range-v3 , you may do: 使用range-v3 ,您可以执行以下操作:

std::vector<int> v{3, 6, 2, 5};
auto r = v | ranges::view::filter([](auto e){ return e > 7; });
auto it = ranges::max_element(r);
if (it == r.end()) {
    std::cout << "End\n";
} else {
    std::cout << *it << std::endl;   
}

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM