[英]map choose `std::greater` or `std::less` at runtime
这一行:
std::map<long int, long int, std::greater<long int>> current_book;
我想用以下逻辑等效替换它:
int Side = ...
if (Side == 1){
std::map<long int, long int, std::greater<long int>> current_book;
} else {
std::map<long int, long int, std::less<long int>> current_book;
}
您可以使用std::function
:
using mymap = std::map<long,long,std::function<bool(long,long)>>;
auto m = Side ? mymap( std::less<long>() ) : mymap( std::greater<long>() );
你必须实现一个自定义比较器类,类似于:
class map_comparator {
bool less_than;
public:
map_comparator(bool less_than) : less_than{less_than} {}
bool operator()(long a, long b) const
{
if (less_than)
return a < b;
return a > b;
}
};
然后使用构造函数来构造映射,该构造函数将比较器类的实例作为参数,然后传入适当构造的比较器类实例:
std::map<long int, long int, map_comparator>
current_book{ map_comparator{ Side != 1}};
您可以使用直线函数指针。 这种方法不会受到每次比较if (less_than)
分支或std::function
开销的开销:
#include <map>
using t_Key = long int;
using t_Value = long int;
using t_Comparator = bool ( * )(t_Key const left, t_Key const right);
using t_Map = ::std::map<t_Key, t_Value, t_Comparator>;
bool Is_Less(t_Key const left, t_Key const right)
{
return left < right;
}
bool Is_Greater(t_Key const left, t_Key const right)
{
return left > right;
}
int main()
{
int Side{};
t_Map current_book{(Side == 1) ? &Is_Less : &Is_Greater};
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.