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

时间:2018-07-26 20:29:31

标签: c++ range-v3

尝试构建采用矢量的代码,先应用视图过滤器,然后进行转换,最后返回最后一个存在的元素:

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()需要基数似乎很奇怪,因为它只需要验证是否有任何个元素,而不是提供确切的元素数。

1 个答案:

答案 0 :(得分:1)

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