c – 需要访问私有类成员的比较器
发布时间:2020-12-16 09:45:21 所属栏目:百科 来源:网络整理
导读:我的代码的基本结构是 class Foo{ vectorstring _lines; vectorint _n; public: ... bool Comp(int i,int j){ return something that depends on _lines; } ... void doSomething(){ std::sort(_n.begin(),_n.end(),Comp); } ...}; 但我明白了 error: no mat
我的代码的基本结构是
class Foo{ vector<string> _lines; vector<int> _n; public: ... bool Comp(int i,int j){ return something that depends on _lines; } ... void doSomething(){ std::sort(_n.begin(),_n.end(),Comp); } ... }; 但我明白了 error: no matching function for call to ‘sort(std::vector<unsigned int>::iterator,std::vector<unsigned int>::iterator,<unresolved overloaded function type>) 如何在不复制矢量的情况下解决此问题? (因为这些向量非常非常大17179508字符串是准确的). 解决方法
std :: sort期望二元谓词在这种情况下采用两个整数.成员函数采用隐式的第一个参数,因此在所有Foo :: Comp中都有三个参数.您可以传递非成员函数或静态成员函数,但这些函数都不能访问Foo的数据成员.简单的方法是使用std :: bind将其绑定到成员函数的第一个参数:
#include <functional> // for std::bind #include <vector> #include <algorithm> class Foo{ vector<string> _lines; vector<int> _n; public: ... bool Comp(int i,int j){ return something that depends on _lines; } ... void sort(){ using namespace std::placeholders; std::sort(_n.begin(),std::bind(Comp,this,_1,_2)); } ... }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- React Server Side Rendering 解决 SPA 应用的 SEO 问题
- 【React Native开发】React Native控件之Touchable*系列组件
- oracle – 存储过程错误PLS-00201:必须声明标识符’UTL_HT
- 【译】SOLID:Part 3 - 里氏代换原则 & 接口隔离原则
- AJAX POST请求中参数以form data和request payload形式在se
- 如何构建需要CocoaPods pod的Appcelerator Titanium iOS模块
- C#实现控制线程池最大数并发线程
- arm学习笔记
- 正则表达式 – 正则表达式修饰符“m”和“s”之间的区别?
- 依赖注入 – 依赖注入:注入部分初始化的对象