需要访问类的私有成员的比较器
Comparator that requires access to private members of class
我的代码的基本结构是
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
期望一个二进制谓词在本例中接受两个int型。成员函数接受隐式的第一个参数,因此在所有Foo::Comp
中接受三个参数。你可以传递一个非成员函数,或者一个静态成员函数,但是它们都不能访问Foo
的数据成员。简单的方法是使用std::bind
将this
绑定到成员函数的第一个参数:
#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(), _n.end(), std::bind(Comp, this, _1, _2));
}
...
};
最明显的初始建议是将int
和string
聚合到一个结构体或std::pair
中,在其中具有聚合的单个向量,然后对聚合向量进行排序。
但如果这两个向量实际上是独立的,我建议使用外部谓词,而不是您的Comp
方法的:
struct Comp
{
explicit Comp(vector<string>& lines) : lines_(lines) { }
bool operator()(int i, int j) const
{
return something that depends on lines_;
}
vector<string>& lines_;
};
然后调用:
void doSomething()
{
std::sort(_n.begin(), _n.end(), Comp(_lines));
}
如何使用您的对象作为比较器本身。
class Foo{
std::vector<std::string> _lines;
std::vector<int> _n;
public:
bool operator()(int i, int j){
return false;
}
void doSomething(){
std::sort(_n.begin(), _n.end(), *this);
}
};
编辑:
事实证明这不是一个好主意,复制一个有17M个字符串的对象会招致巨大的损失。可以使用带指针的嵌套类来代替。这也允许我们有不同的比较器:
class Foo
{
std::vector<std::string> _lines;
std::vector<int> _n;
class Bar
{
public:
Bar( const Foo * foo ) : _foo( foo ) {}
bool operator()( int i, int j )
{
act on _foo->_lines
}
private:
const Foo * _foo;
};
public:
void doSomething(){
std::sort(_n.begin(), _n.end(), Bar(this));
}
};
相关文章:
- std::设置自定义比较器
- C++中"std::sort"比较器的不同类型
- 将 std::set 与基于键的比较器一起使用
- 带自定义比较器的最小优先级队列
- 函数类作为比较器
- 优先级队列自定义比较器
- 什么是自定义比较器以及如何在 C++ 的排序函数中使用它?
- 没有默认构造函数作为模板参数的自定义比较器
- 为什么我需要在成员发起器列表中重复基类的模板参数?
- 用于基于成员字段或函数创建比较器的快捷方式
- 如何使用自定义比较器初始化类数据成员,该成员是 std::set
- 将比较器传递给Priority_queue,称为班级成员
- C++使用成员字段设置比较器
- 调用 std::等于时出错,将类成员函数作为比较器
- 成员功能作为映射比较器
- 访问类的私有成员的自定义优先级队列比较器
- 需要访问类的私有成员的比较器
- C++std列表排序使用自定义比较器,该比较器依赖于对象实例的成员变量
- 以指向成员的指针作为比较器/"key"的 STD 算法
- 从集合<A*,比较器>中获取A成员以列出<A>