在c++20中使用视图管道和范围adjacent_find时如何修复无效迭代器错误

问题描述 投票:0回答:1

我试图检查嵌套向量中的所有值是否相同/唯一。我写了这个程序(简化了,但同样的错误):

神箭链接

#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>

auto main() -> int
{
    std::vector<std::vector<int>> vectors_of_ints {
        {1, 2, 3},
        {4, 5, 6}
    };

    auto get_vectors = [](const std::vector<int>& v) { return v; };
    auto get_ints = [](const int& i) { return i; };

    auto all_ints = vectors_of_ints
           | std::views::transform(get_vectors)
           | std::views::join
           | std::views::transform(get_ints);


    auto status = std::ranges::adjacent_find(all_ints, std::not_equal_to{}) != std::ranges::end(all_ints);

    return status;
}

但我收到此错误:

<source>:22:44: error: no match for call to '(const std::ranges::__adjacent_find_fn) (std::ranges::transform_view<std::ranges::join_view<std::ranges::transform_view<std::ranges::ref_view<std::vector<std::vector<int> > >, main()::<lambda(const std::vector<int>&)> > >, main()::<lambda(const int&)> >&, std::not_equal_to<void>)'
   22 |     std::cout << std::ranges::adjacent_find(all_ints, std::not_equal_to{}) != std::ranges::end(all_ints);
      |                  ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[...] // too long to post
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bits/ranges_base.h:594:13:   required for the satisfaction of 'forward_range<_Range>' [with _Range = std::ranges::transform_view<std::ranges::join_view<std::ranges::transform_view<std::ranges::ref_view<std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > >, main::._anon_112> >, main::._anon_113>&]
/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/concepts:67:28: note:   'std::forward_iterator_tag' is not a base of 'std::input_iterator_tag'
   67 |     concept derived_from = __is_base_of(_Base, _Derived)
      |                            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Compiler returned: 1

结论是:

std::forward_iterator_tag is not a base of std::input_iterator_tag

我想了解我遇到的问题以及如何解决该问题。

c++ algorithm view range c++20
1个回答
0
投票

如果您不想显式复制容器,则简单

auto all_ints = vectors_of_ints | std::views::join;

有效。

如果您确实想复制内容,请考虑从

all_ints
:

创建一个新向量
std::vector<int> all_ints_copy(all_ints.begin(), all_ints.end());

在 C++23 中

std::ranges::to
简化了此过程并减少了所有副本的数量:

auto all_ints_copy_to = vectors_of_ints
                    | std::views::join
                    | std::ranges::to<std::vector<int>>();

查看演示

© www.soinside.com 2019 - 2024. All rights reserved.