簡體   English   中英

map在運行時選擇`std :: greater`或`std :: less`

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM