![](/img/trans.png)
[英]If std::greater<>, then why std::less (and not std::lesser<>)?
[英]delegate std::less or std::greater in condition
我已經實現了一個測試用例,我可以將key作為自定義類,如下所示:
#include <iostream>
#include <map>
using namespace std;
class CoordinateValue
{
public:
short int x_;
short int y_;
CoordinateValue(short int x = 0, short int y = 0)
: x_(x),y_(y)
{
}
bool operator<=(const CoordinateValue &right) const
{
return ((this->x_ <= right.x_) && (this->y_ <= right.y_));
}
bool operator<(const CoordinateValue &right) const
{
return ((this->x_ < right.x_) && (this->y_ < right.y_));
}
bool operator>=(const CoordinateValue &right) const
{
return ((this->x_ >= right.x_) && (this->y_ >= right.y_));
}
bool operator>(const CoordinateValue &right) const
{
return ((this->x_ > right.x_) && (this->y_ > right.y_));
}
friend ostream &operator<<(ostream &out, const CoordinateValue &val)
{
out << "[ " << val.x_ << "," << val.y_ << " ]" << std::endl;
return out;
}
} ;
int main()
{
std::multimap<CoordinateValue,int,std::less_equal<CoordinateValue>> intersectionIn;
intersectionIn.insert(std::pair<CoordinateValue,int>(CoordinateValue(100,200),12));
intersectionIn.insert(std::pair<CoordinateValue,int>(CoordinateValue(1000,7),135));
intersectionIn.insert(std::pair<CoordinateValue,int>(CoordinateValue(0,2),112));
intersectionIn.insert(std::pair<CoordinateValue,int>(CoordinateValue(-10,-200),12));
intersectionIn.insert(std::pair<CoordinateValue,int>(CoordinateValue(-100,-200),12));
intersectionIn.insert(std::pair<CoordinateValue,int>(CoordinateValue(1000,2000),12));
std::multimap<CoordinateValue,int,std::greater<CoordinateValue>>::const_iterator iter = intersectionIn.begin();
while(iter != intersectionIn.end())
{
std::cout << iter->first;
++iter;
}
return 0;
}
現在我想根據某些條件調用std :: greater / std :: less / std :: less_equal。 如何委托? 例如,對於一個條件,我使用std :: less聲明容器,對於其他條件,我使用std :: greater聲明容器。
一些提示或參考將是偉大的。
謝謝
看起來你想要一個運行時版本(從你的注釋中),你可以使用類型std::function<bool(int, int)>
作為你在multimap
的Compare
類型,然后存儲std::less
或std::greater
在創建地圖時:
std::function<bool(int, int)> cmp;
if (...) {
cmp = std::less<int>();
}
else {
cmp = std::greater<int>();
}
std::multimap<int, int, decltype(cmp)> map(cmp);
關於ideone的代碼: http ://ideone.com/cP0OEm
下面的舊編譯時間版本:
如果你可以使用c++11
,你可以使用std::conditional
:
template <typename T>
using cmp = typename std::conditional<cond, std::greater<T>, std::less<T>>::type;
cond
是你的條件,你可以鏈接std::conditional
多條件。
接着:
std::multimap<int, int, cmp<int>> map;
由於您沒有說明您的條件,我無法添加更多信息。
您的評論后,這可能如下所示:
template <int value, typename T>
using cmp = typename std::conditional<(value > 0), std::less<T>, std::greater<T>>::type;
std::multimap<int, int, cmp<MY_VALUE, int>> map;
其中MY_VALUE
是編譯時常量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.