此问题在此处已有答案:
Using custom std::set comparator(7个答案)
17天前关闭。
此帖子已于9天前编辑并提交审核,未能重新打开帖子:
原始关闭原因未解决
如何为下面的例子指定自定义比较?其思想是访问类中的成员变量进行比较。
struct MyStruct {
unsigned p;
unsigned t;
};
class MyClass {
public:
void call() {
ob["o1_10"] ={10, 1};
mbp[ob["o1_10"].p].insert("o1_10");
ob["o2_20_2"] ={20, 2};
mbp[ob["o2_20"].p].insert("o2_20");
ob["o4_4_4"] ={4, 4};
mbp[ob["o4_4"].p].insert("o4_4");
ob["o5_10"] ={10, 4};
mbp[ob["o5_10"].p].insert("o5_10");
}
private:
map<unsigned,set<string, Compare>> mbp;
// Question: how to define compare using struct, operator(), statice metthod or external method so that
// compare fetches ob[ol] and ob[0l2] and decide based on some rules
// so, comparions is not based on ol and o2 and it is based on some p and t in ob[o1] and ob[02]
// Eg:
// bool compare(const string& o1, const string& o2) const {
// if (ob.at(o1).p > ob.at(o2).p) return true;
// if (ob.at(o1).p == ob.at(o2).p && ob.at(o1).t < ob.at(o2).t) return true;
// return false;
// }
map<string, MyStruct> ob;
};
int main() {
MyClass my_class;
my_class.call();
return 0;
}
字符串
需要注意的是,比较键并不是类的示例,相反,我想使用键访问类的示例进行比较,如果可以实现这一点,我就可以保存一些内存。
我试过以下方法,但每种方法都给我不同的错误给予:
1.类内结构
1.函子
1.使用绑定
1条答案
按热度按时间aiqt4smr1#
你需要像this一样重载
operator<
。有了这个操作符,你可以在
std::set
和std::map
中使用你的类(作为键)。在实践中,你可能还想重载所有的比较操作符(For C++20 overload the spaceship operator instead)。字符串