[英]std::set with custom comparator operator on object at compile time
我有一個包含 std::set 作為成員變量的類(即 A)。 現在我想創建 2 個 A 類對象,以便:
class A {
std::set<int, <magic custom operator>>;
};
A obj1 - Ascending order
A obj2 - Descending order
如何在編譯(運行)時實現此功能,以便集合將根據對象按升序或降序保存對象。
非常感謝您對此的任何幫助。
您的比較器可以有狀態。 例如,
struct StatefulComparator {
StatefulComparator(bool b) : ascending_(b) {}
bool operator()(int lhs, int rhs) const {
return ascending_
? lhs < rhs
: lhs > rhs;
}
bool ascending_;
};
然后將比較器傳遞給 set 構造函數:
std::set<int, StatefulComparator> ascendingSet (StatefulComparator(true));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.