问题描述
例如,如果我想找到集合中最小的元素,但只找到最小的 even 元素,我想使用 ranges :: min_element
过滤范围如下:
For example, if I want to find the smallest element of a collection, but only the smallest even element, I'd like to call ranges::min_element
with a filtered range like so:
using ranges::views::filter;
using ranges::min_element;
std::vector<int> vals{1,2,3,4,5};
auto minVal = min_element(vals | filter([](int next){return next % 2 == 0;}));
如何检查返回的范围是否为空,如果不是,则访问该值?
其他范围算法也是如此,例如 ranges :: find
, ranges :: find_if
等.
推荐答案
很遗憾,您无法将临时范围传递给范围算法.
Unfortunately you cannot pass a temporary range into ranges algorithms.
这是因为它们在完成后将返回范围迭代器(可能是 ranges :: end(rng)
).如果您传递了一个临时变量,则返回的迭代器将无效;引用一个临时的.Ranges库检测到此情况并返回一个虚拟的哨兵 ranges :: dangling
而不是迭代器.
This is because they will return a ranges iterator (possibly ranges::end(rng)
) upon completion. If you pass a temporary, the returned iterator would be invalid; referencing a temporary. The ranges library detects this and returns a dummy sentinel, ranges::dangling
instead of an iterator.
执行此操作的正确方法是首先组成过滤范围,然后 调用算法.
The proper way to do this is to first compose your filtered range then call the algorithm.
std::vector<int> vals {1, 2, 3, 4, 5};
auto even_vals = vals | filter([](int val){return val % 2 == 0;});
auto minVal = min_element(even_vals);
if (minVal == even_vals.end())
std::cout << "no values\n";
else
std::cout << *minVal; // prints "2"
这篇关于如何检查range ::算法(例如find_if)是否返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!