C++std列表排序使用自定义比较器,该比较器依赖于对象实例的成员变量
C++ std list sort with custom comparator that depends on an member variable for the object instance
类别:
Class:
private:
...
vector<string> words;
vector< list<int> > vints;
public:
myFunction(...)
我正在调用另一个成员函数中的非空列表排序:
void myClass::myFunction (...) {
...
if (!vints[i].empty()) vints[i].sort(sortFunc);
...
}
我的排序功能:
bool myClass::sortFunc(const int& i, const int& j) { return (words[i] < words[j]); }
错误:
error: no matching function for call to ‘std::list<int, std::allocator<int> >::sort(<unresolved overloaded function type>)’
/usr/include/c++/4.4/bits/list.tcc:301: note: candidates are: void std::list<_Tp, _Alloc>::sort() [with _Tp = int, _Alloc = std::allocator<int>]
/usr/include/c++/4.4/bits/list.tcc:378: note: void std::list<_Tp, _ Alloc>::sort(_StrictWeakOrdering) [with _StrictWeakOrdering = bool (SuperWordSearch::*) (const int&, const int&), _Tp = int, _Alloc = std::allocator<int>]
我研究并遇到了以下问题:
C++自定义列表比较功能:排序
排序指针列表时出现问题
使用自定义比较器进行std::list::排序时出错(应为';之前的主表达式(';代币(
如果不是因为在这个类中,sortFunc依赖于对象实例的成员变量WORDS,它们就足够了。所以我不能使比较器函数(sortFunc(静态或全局
编辑:刚刚遇到这个问题。当你需要成员数据时,如何对std:list进行排序?它通过创建一个友元类提供了一个解决方案,但有可能在用户定义的类内部实现这一点吗?
带lambdas:
vints[i].sort([&words](int i, int j) { return words[i] < words[j]; });
带std::bind
:
#include <functional>
//...
{
using namespace std::placeholders;
vints[i].sort(std::bind(&myClass::sortFunc, this, _1, _2));
}
@Kerrek涉及lambdas的答案更好。但是,如果必须避免C++11的特性,那么用函子替换排序函数。允许该函数存储对所需数据的引用,如下所示:
#include <vector>
#include <list>
#include <string>
class myClass {
private:
std::vector<std::string> words;
std::vector<std::list<int> > vints;
// Instead of sortFunc, use sortFunctor. A functor can be used in place
// of a function in many places, and it can carry state (like a reference
// to the data it needs).
struct sortFunctor {
const std::vector<std::string>& words;
sortFunctor(const std::vector<std::string>& words) : words(words) { }
bool operator()(int i, int j) { return words[i] < words[j]; }
};
public:
void myFunction() {
vints[0].sort(sortFunctor(words));
}
myClass() {
words.push_back("apple");
words.push_back("berry");
std::list<int> l;
l.push_back(0);
l.push_back(1);
vints.push_back(l);
}
};
int main () {
myClass object;
object.myFunction();
}
相关文章:
- 对于BTreeMap和其他依赖于Ord的东西,是否有等效于C++比较器对象?
- std::用派生类对象设置,但用gcc8.1设置基类比较器
- 基于对象的两个属性的自定义比较器会引发异常
- 是在STL中使用的COMP比较器是从未更改的STL比较比较STL中的对象
- C++:对象键的多映射自定义比较器
- 如何实现分类比较器,以级联相关对象
- c++中一对对象的映射比较器
- 将STD ::指针列表与比较器的对象列表
- 为指针后面的对象创建比较器的通用方法
- 包含指向对象的指针的多集的自定义比较器
- 对象的比较器运算符,用于将其存储在地图中
- C++ 集<>类对象。使用自己的比较器给出错误:C2804:二进制'operator <'参数过多
- C++ 集<>类对象。使用自己的比较器给出来自功能,xtree等的错误 JUNK
- 传递依赖于对象的比较器作为模板参数,
- C++std列表排序使用自定义比较器,该比较器依赖于对象实例的成员变量
- 定义<比较器时按降序对对象进行排序?
- 比较器,用于对包含指向自定义类对象的指针的向量进行排序
- 在 c++ 中为对对象定义排序函数的比较器
- 使用自定义函数对象比较器 c++ 设置
- 标准算法比较器接受不同类型的对象是否合法?