尝试确定转换后的范围是否为空

Attempting to determine if a transformed range is empty

正在尝试构建采用向量、应用视图过滤器然后进行转换的代码,最后返回最后一个元素(如果存在):

int foo()
{
  std::vector<int> v = {0, 1, 5, 3, 8, 9};
  auto r =
    v
    | view::filter([] (auto i) { return i % 2 == 0; })
    | view::transform([] (auto i) { return i * 2; });

  return r.empty() ? 0 : r.back();
}

编译会导致以下错误:

test.cpp: In function 'int foo()':
test.cpp:14:18: error: no matching function for call to 'ranges::v3::transform_view<ran
ges::v3::remove_if_view<ranges::v3::iterator_range<__gnu_cxx::__normal_iterator<int*, std::vector<int> >, __gnu_cxx::__normal_iterator<int*
, std::vector<int> > >, ranges::v3::logical_negate_<foo()::<lambda(auto:1)> > >, foo()::<lambda(auto:2)> >::empty()'
   return r.empty() ? 0 : r.back();
                  ^
In file included from range-v3/include/range/v3/view_facade.hpp:21:0,
                 from range-v3/include/range/v3/core.hpp:21,
                 from range-v3/include/range/v3/all.hpp:17,
                 from test.cpp:1:
range-v3/include/range/v3/view_interface.hpp:88:28: note: candidate: template<in
t _concept_requires_87, typename std::enable_if<((_concept_requires_87 == 43) || ((ranges::v3::cardinality)-1 >= 0)), int>::type <anonymous
> > constexpr bool ranges::v3::view_interface<Derived, <anonymous> >::empty() const [with int _concept_requires_87 = _concept_requires_87;
typename std::enable_if<((_concept_requires_87 == 43) || (Cardinality >= 0)), int>::type <anonymous> = <enumerator>; Derived = ranges::v3::
iter_transform_view<ranges::v3::remove_if_view<ranges::v3::iterator_range<__gnu_cxx::__normal_iterator<int*, std::vector<int> >, __gnu_cxx:
:__normal_iterator<int*, std::vector<int> > >, ranges::v3::logical_negate_<foo()::<lambda(auto:1)> > >, ranges::v3::indirected<foo()::<lamb
da(auto:2)> > >; ranges::v3::cardinality Cardinality = (ranges::v3::cardinality)-1]

所以,看起来 transform_view 缺少基数概念,不管它是在转换后的向量上运行的。是否有可以应用于允许此代码工作的范围的运算符? empty() 需要基数似乎很奇怪,因为它只需要验证是否有 any 元素而不是提供元素的确切数量。

view::filter 在旧版本的 range-v3 中产生了 InputRange,因此不提供 emptyback(以避免人们编写错误他们在输入视图上重复调用 begin)。您需要 range-v3 0.3.6 或 trunk,如果基础范围是双向的,其中 view::filter 是双向的。