[英]Modify std::less on a shared_ptr
這就是我所擁有的:
struct Foo {
int index;
}
std::set<std::shared_ptr<Foo>> bar;
我想通過它們的索引而不是通過默認的std::less<std::shared_ptr<T>>
函數來對bar
的元素進行排序,該函數與指針相關。
我讀到我可以鍵入
std::set<std::shared_ptr<Foo>, std::owner_less<std::shared_ptr<Foo>>> bar
,但是我更喜歡堅持以前的語法。
我嘗試定義std::less<std::shared_ptr<Foo>>
,但是set
函數實際上並未使用它。 有沒有辦法可以做到這一點?
如果要按其索引進行比較,則必須編寫一個按其索引進行檢查的比較器。 std::less<>
會做錯事(因為它不會知道index
),而std::owner_less<>
會做錯事(因為它仍然不會比較Foo
,但是必須這樣做以及它們的所有權語義)。
您必須寫:
struct SharedFooComparator {
bool operator()(const std::shared_ptr<Foo>& lhs,
const std::shared_ptr<Foo>& rhs) const
{
return lhs->index < rhs->index;
}
};
並使用它:
std::set<std::shared_ptr<Foo>, SharedFooComparator> bar;
您還可以將其通用化為shared_ptr的通用比較器:
struct SharedComparator {
template <typename T>
bool operator()(const std::shared_ptr<T>& lhs,
const std::shared_ptr<T>& rhs) const
{
return (*lhs) < (*rhs);
}
};
然后簡單地使Foo
具有可比性。
您可以在std
名稱空間中提供您自己的less<shared_ptr<Foo>>
專業化。
namespace std
{
template<>
class less<shared_ptr<Foo>>
{
public:
bool operator()(const shared_ptr<Event>& a, const shared_ptr<Event>& b)
{
// Compare *a and *b in some way
}
};
}
然后,您可以在沒有比較器的情況下形成set<shared_ptr<Foo>>
。 我需要一個priority_queue<shared_ptr<Foo>>
,我不想在其中使用priority_queue<Foo*, vector<Foo*>, int (*)(const Foo*, const Foo*)>
。 我不為此感到驕傲,但它確實有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.