加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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));
  }
  ...
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读