C ++动态分配std :: map比较器 [英] C++ Dynamically assign std::map comparator

查看:302
本文介绍了C ++动态分配std :: map比较器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有两个类包含std :: map成员,具有相同的功能,除了一个地图的顺序是std :: less,另一个std ::更大。



如果我创建一个抽象的父类并声明一个映射成员,有没有办法在派生类构造函数中为这个成员动态分配比较器?这样一来,这个功能显然可以放在父类中。

解决方案

事实之后,您不能更改比较器。但是您可以使用相同的比较器类,并在施工时获得较大或较小。你只需要一个有状态的比较器:

  struct my_compare {
enum compare_type {less,greater};
explicit my_compare(compare_type t):m_type(t){}
template< class T,class U>
bool operator()(const T& t,const U& u)const {
if(m_type == less){return t < U; }
else {return t> U; }
}
compare_type m_type;
};

然后你可以做

  std :: map< int,int,my_compare> less_map((my_compare(my_compare ::更少))); 
std :: map< int,int,my_compare> greater_map((my_compare(my_compare ::更大)));

额外的圆括号是因为否则将是最令人烦恼的解析,即使函数参数声明不具有限定名称 。在C ++ 11中,可以使用列表初始化( my_compare {mycompare :: less} )。






对于您的具体设计,实现可能看起来像

  class A {
protected:
A(my_compare :: compare_type ct):my_map(my_compare(ct)){}
std :: map< int,int,my_compare> my_map;
};

class B_less:public A {
public:
B_less():A(my_compare :: less){}
};


So I have two classes containing std::map members with effectively identical functionality except that the ordering of one map is std::less and the other std::greater.

If I create an abstract parent class and declare a single map member, is there any way to dynamically assign the comparator for this member in the derived class constructors? That way the functionality can obviously all reside in the parent class.

解决方案

You can't change the comparator after the fact. But you can use the same comparator class and get either "greater" or "less" at the time of construction. You just need a stateful comparator:

struct my_compare {
    enum compare_type { less, greater };
    explicit my_compare(compare_type t) : m_type(t) {}
    template<class T, class U>
    bool operator()(const T& t, const U& u) const {
        if(m_type == less) { return t < u; }
        else { return t > u; }
    }
    compare_type m_type;
};

Then you can do

std::map<int, int, my_compare> less_map((my_compare(my_compare::less)));
std::map<int, int, my_compare> greater_map((my_compare(my_compare::greater)));

The extra pair of parentheses is because it would otherwise be the most vexing parse , even though a function parameter declaration cannot have a qualified name. In C++11, list-initialization (my_compare{mycompare::less}) can be used instead.


For your specific design, an implementation might look like

class A {
protected:
    A(my_compare::compare_type ct) : my_map(my_compare(ct)) {}
    std::map<int, int, my_compare> my_map;
};

class B_less : public A{
public:
    B_less() : A(my_compare::less) {}
};

这篇关于C ++动态分配std :: map比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆