[英]Sorting order of std::map depending on an input value
I know that you cannot change the ordering of a map once declared. 我知道一旦声明你就无法改变地图的顺序。 Instead I am trying this in a struct:
相反,我在一个结构中尝试这个:
struct MyStruct
{
std::map<int, double>* my_map;
MyStruct(bool dir)
{
if(dir)
{
my_map = new std::map<int, double, std::less<int> >;
}
else
{
my_map = new std::map<int, double, std::greater<int> >;
}
}
}
This isn't working and complains that I am changing the type under the else
condition. 这不起作用,并抱怨我在
else
条件下更改类型。 Is there a way around this? 有没有解决的办法? The only way I can think of is to write my own comparator and to create an object encapsulating
bool dir
which seems redundant. 我能想到的唯一方法是编写自己的比较器并创建一个封装
bool dir
的对象,这似乎是多余的。
std::map
takes the comparison object as a template parameter, so to do what you want you need a type that you can change the behaviour at runtime. std::map
将比较对象作为模板参数,因此要执行您想要的类型,您可以在运行时更改行为。
struct MoreOrLess
{
bool useLess;
template <class T, class U>
bool operator()(const T &t, const U &u) const
{
if(useLess) return t < u;
else return t > u;
}
};
struct MyStruct
{
std::map<int, double, MoreOrLess> my_map;
MyStruct(bool dir) :my_map(MoreOrLess{dir}) {}
};
This way the comparison functor has the same type (for use in std::map
) regardless of using std::less
or std::greater
. 这样,无论使用
std::less
还是std::greater
,比较仿函数都具有相同的类型(用于std::map
)。
Here is a simple approach, although probably not the most efficient: 这是一个简单的方法,虽然可能不是最有效的方法:
struct MyStruct
{
typedef std::function<bool(int,int)> Predicate;
std::map<int,double,Predicate> my_map;
static Predicate predicateFor(bool dir)
{
if (dir) return std::less<int>();
return std::greater<int>();
}
MyStruct(bool dir) : my_map(predicateFor(dir)) { }
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.