使迭代器与 std::ranges 函数一起工作

如何解决使迭代器与 std::ranges 函数一起工作

我有以下二维网格迭代器代码。

#include <algorithm>
using std::ranges::count_if;
using std::ranges::for_each;

#include <iostream>
using std::endl;
using std::cout;

#include <iterator>
using std::iterator;
using std::forward_iterator_tag;

#include <memory>
using std::make_shared;
using std::shared_ptr;

#include <stdexcept>
using std::invalid_argument;

#include <vector>
using std::vector;


template <typename T>
class Grid2D;
    
template <typename T>
class Grid2DIterator : public iterator<forward_iterator_tag,T> {
private:
    Grid2D<T> & grid;
    size_t index;

    size_t getX() const
    {
        return index % grid.sizeX();
    }

    size_t getY() const
    {
        return index / grid.sizeX();
    }
public:
    using iterator = Grid2DIterator<T>;

    Grid2DIterator(Grid2D<T> * grid,size_t index)
        : grid(*grid),index(index)
    {}

    Grid2DIterator()
        : Grid2DIterator(nullptr,0)
    {}

    T & operator*() {
        return grid(getX(),getY());
    }
    
    Grid2DIterator & operator++() {
        ++index;
        return *this;
    }
    
    bool operator==(Grid2DIterator const & other) const {
        return other.grid == grid && index == other.index;
    }
    
    bool operator!=(Grid2DIterator const & other) const {
        return !(*this == other);
    }
};


template <typename T>
class Grid2D {
private:
    vector<vector<T>> grid;
public:
    Grid2D(size_t x,size_t y,T const & init);
    Grid2D(vector<vector<T>> const & grid);
    
    T const & operator()(size_t x,size_t y) const;
    T & operator()(size_t x,size_t y);
    bool operator==(Grid2D<T> const & other) const;
    
    size_t sizeX() const;
    size_t sizeY() const;
    size_t size() const;
    
    Grid2DIterator<T> begin();
    Grid2DIterator<T> end();
};


template <typename T>
Grid2D<T>::Grid2D(size_t x,T const & init)
    : grid(y,vector<T>(x,init))
{
    if (x < 1)
        throw invalid_argument("x must be >= 1");
        
    if (y < 1)
        throw invalid_argument("y must be >= 1");
}

template <typename T>
Grid2D<T>::Grid2D(vector<vector<T>> const & grid)
    : grid(grid)
{}

template <typename T>
T const & Grid2D<T>::operator()(size_t x,size_t y) const
{
    return grid.at(y).at(x);
}

template <typename T>
T & Grid2D<T>::operator()(size_t x,size_t y)
{
    return grid.at(y).at(x);
}

template <typename T>
bool Grid2D<T>::operator==(Grid2D<T> const & other) const
{
    return sizeX() == other.sizeX() && sizeY() == other.sizeY();
}

template <typename T>
size_t Grid2D<T>::sizeX() const
{
    return grid[0].size();
}

template <typename T>
size_t Grid2D<T>::sizeY() const
{
    return grid.size();
}

template <typename T>
size_t Grid2D<T>::size() const
{
    return sizeX() * sizeY();
}

template <typename T>
Grid2DIterator<T> Grid2D<T>::begin()
{
    return Grid2DIterator(this,0);
}

template <typename T>
Grid2DIterator<T> Grid2D<T>::end()
{
    return Grid2DIterator(this,sizeX() * sizeY());
}

int main()
{
    vector<vector<int>> vec = {
        {1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25}
    };
    Grid2D<int> grid(vec);
    for_each(grid,[] (auto const & item) { cout << item << endl; });
    auto cnt = count_if(grid,[] (auto const & i) { return i > 7; });
    cout << "Count: " << cnt << endl;
}

在使用 algorithmGrid2D::begin()Grid2D::end() 中的标准迭代器函数时,它工作正常。 但是,当我直接将 Grid2D 实例传递给 std::ranges 中的函数时,我的代码不起作用。由于模板溢出,我收到的错误消息非常神秘,但它是这样的:

$ LANG=C g++ --std=c++20 grid.cpp -o grid
grid.cpp: In function 'int main()':
grid.cpp:167:13: error: no match for call to '(const std::ranges::__for_each_fn) (Grid2D<int>&,main()::<lambda(const auto:19&)>)'
  167 |     for_each(grid,[] (auto const & item) { cout << item << endl; });
      |     ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/11.1.0/algorithm:64,from grid.cpp:1:
/usr/include/c++/11.1.0/bits/ranges_algo.h:184:7: note: candidate: 'template<class _Iter,class _Sent,class _Proj,class _Fun>  requires (input_iterator<_Iter>) && (sentinel_for<_Sent,_Iter>) && (indirectly_unary_invocable<_Fun,std::projected<_Iter,_Proj> >) constexpr std::ranges::for_each_result<_Iter,_Fun> std::ranges::__for_each_fn::operator()(_Iter,_Sent,_Fun,_Proj) const'
  184 |       operator()(_Iter __first,_Sent __last,_Fun __f,_Proj __proj = {}) const
      |       ^~~~~~~~
/usr/include/c++/11.1.0/bits/ranges_algo.h:184:7: note:   template argument deduction/substitution failed:
grid.cpp:167:13: note:   candidate expects 4 arguments,2 provided
  167 |     for_each(grid,from grid.cpp:1:
/usr/include/c++/11.1.0/bits/ranges_algo.h:195:7: note: candidate: 'template<class _Range,class _Fun>  requires (input_range<_Range>) && (indirectly_unary_invocable<_Fun,std::projected<decltype(std::__detail::__ranges_begin((declval<_Container&>)())),_Proj> >) constexpr std::ranges::for_each_result<std::ranges::borrowed_iterator_t<_Range>,_Fun> std::ranges::__for_each_fn::operator()(_Range&&,_Proj) const'
  195 |       operator()(_Range&& __r,_Proj __proj = {}) const
      |       ^~~~~~~~
/usr/include/c++/11.1.0/bits/ranges_algo.h:195:7: note:   template argument deduction/substitution failed:
/usr/include/c++/11.1.0/bits/ranges_algo.h:195:7: note: constraints not satisfied
In file included from /usr/include/c++/11.1.0/string_view:44,from /usr/include/c++/11.1.0/bits/basic_string.h:48,from /usr/include/c++/11.1.0/string:55,from /usr/include/c++/11.1.0/bits/locale_classes.h:40,from /usr/include/c++/11.1.0/bits/ios_base.h:41,from /usr/include/c++/11.1.0/streambuf:41,from /usr/include/c++/11.1.0/bits/streambuf_iterator.h:35,from /usr/include/c++/11.1.0/iterator:66,from /usr/include/c++/11.1.0/bits/ranges_algobase.h:36,from /usr/include/c++/11.1.0/bits/ranges_algo.h:35,from /usr/include/c++/11.1.0/algorithm:64,from grid.cpp:1:
/usr/include/c++/11.1.0/bits/ranges_base.h: In substitution of 'template<class _Range,_Proj) const [with _Range = Grid2D<int>&; _Proj = std::identity; _Fun = main()::<lambda(const auto:19&)>]':
grid.cpp:167:13:   required from here
/usr/include/c++/11.1.0/bits/ranges_base.h:579:13:   required for the satisfaction of 'range<_Tp>' [with _Tp = Grid2D<int>&]
/usr/include/c++/11.1.0/bits/ranges_base.h:639:13:   required for the satisfaction of 'input_range<_Range>' [with _Range = Grid2D<int>&]
/usr/include/c++/11.1.0/bits/ranges_base.h:579:21:   in requirements with '_Tp& __t' [with _Tp = Grid2D<int>&]
/usr/include/c++/11.1.0/bits/ranges_base.h:581:22: note: the required expression 'std::ranges::__cust::begin(__t)' is invalid
  581 |         ranges::begin(__t);
      |         ~~~~~~~~~~~~~^~~~~
/usr/include/c++/11.1.0/bits/ranges_base.h:582:20: note: the required expression 'std::ranges::__cust::end(__t)' is invalid
  582 |         ranges::end(__t);
      |         ~~~~~~~~~~~^~~~~
cc1plus: note: set '-fconcepts-diagnostics-depth=' to at least 2 for more detail
grid.cpp:168:24: error: no match for call to '(const std::ranges::__count_if_fn) (Grid2D<int>&,main()::<lambda(const auto:20&)>)'
  168 |     auto cnt = count_if(grid,[] (auto const & i) { return i > 7; });
      |                ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/11.1.0/algorithm:64,from grid.cpp:1:
/usr/include/c++/11.1.0/bits/ranges_algo.h:400:7: note: candidate: 'template<class _Iter,class _Pred>  requires (input_iterator<_Iter>) && (sentinel_for<_Sent,_Iter>) && (indirect_unary_predicate<_Pred,_Proj> >) constexpr std::iter_difference_t<_Iter> std::ranges::__count_if_fn::operator()(_Iter,_Pred,_Proj) const'
  400 |       operator()(_Iter __first,|       ^~~~~~~~
/usr/include/c++/11.1.0/bits/ranges_algo.h:400:7: note:   template argument deduction/substitution failed:
grid.cpp:168:24: note:   candidate expects 4 arguments,2 provided
  168 |     auto cnt = count_if(grid,from grid.cpp:1:
/usr/include/c++/11.1.0/bits/ranges_algo.h:415:7: note: candidate: 'template<class _Range,class _Pred>  requires (input_range<_Range>) && (indirect_unary_predicate<_Pred,_Proj> >) constexpr std::ranges::range_difference_t<_Range> std::ranges::__count_if_fn::operator()(_Range&&,_Proj) const'
  415 |       operator()(_Range&& __r,_Pred __pred,_Proj __proj = {}) const
      |       ^~~~~~~~
/usr/include/c++/11.1.0/bits/ranges_algo.h:415:7: note:   template argument deduction/substitution failed:
/usr/include/c++/11.1.0/bits/ranges_algo.h:415:7: note: constraints not satisfied
In file included from /usr/include/c++/11.1.0/string_view:44,_Proj) const [with _Range = Grid2D<int>&; _Proj = std::identity; _Pred = main()::<lambda(const auto:20&)>]':
grid.cpp:168:24:   required from here
/usr/include/c++/11.1.0/bits/ranges_base.h:579:13:   required for the satisfaction of 'range<_Tp>' [with _Tp = Grid2D<int>&]
/usr/include/c++/11.1.0/bits/ranges_base.h:639:13:   required for the satisfaction of 'input_range<_Range>' [with _Range = Grid2D<int>&]
/usr/include/c++/11.1.0/bits/ranges_base.h:579:21:   in requirements with '_Tp& __t' [with _Tp = Grid2D<int>&]
/usr/include/c++/11.1.0/bits/ranges_base.h:581:22: note: the required expression 'std::ranges::__cust::begin(__t)' is invalid
  581 |         ranges::begin(__t);
      |         ~~~~~~~~~~~~~^~~~~
/usr/include/c++/11.1.0/bits/ranges_base.h:582:20: note: the required expression 'std::ranges::__cust::end(__t)' is invalid
  582 |         ranges::end(__t);
      |         ~~~~~~~~~~~^~~~~

我必须实施/更改什么才能使我的 Grid2D 模板可用于 std::ranges:: 函数?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res