简体   繁体   English

在shared_ptr上修改std :: less

[英]Modify std::less on a shared_ptr

This is what I have: 这就是我所拥有的:

struct Foo {
  int index;
}
std::set<std::shared_ptr<Foo>> bar;

I want to order bar 's elements by their indices instead of by the default std::less<std::shared_ptr<T>> function, which relates the pointers. 我想通过它们的索引而不是通过默认的std::less<std::shared_ptr<T>>函数来对bar的元素进行排序,该函数与指针相关。

I read I can type std::set<std::shared_ptr<Foo>, std::owner_less<std::shared_ptr<Foo>>> bar , but I'd prefer to stick to the previous syntax. 我读到我可以键入 std::set<std::shared_ptr<Foo>, std::owner_less<std::shared_ptr<Foo>>> bar ,但是我更喜欢坚持以前的语法。

I tried defining std::less<std::shared_ptr<Foo>> , but it's not actually being used by the set functions. 我尝试定义std::less<std::shared_ptr<Foo>> ,但是set函数实际上并未使用它。 Is there a way I can achieve this? 有没有办法可以做到这一点?

If you want to compare by their indices, you'll have to write a comparator that checks by their indices. 如果要按其索引进行比较,则必须编写一个按其索引进行检查的比较器。 std::less<> will do the wrong thing (since it won't know about index ) and std::owner_less<> will do the wrong thing (since it still won't compare the Foo s, but rather has to do with ownership semantics of them). std::less<>会做错事(因为它不会知道index ),而std::owner_less<>会做错事(因为它仍然不会比较Foo ,但是必须这样做以及它们的所有权语义)。

You have to write: 您必须写:

struct SharedFooComparator {
    bool operator()(const std::shared_ptr<Foo>& lhs,
                    const std::shared_ptr<Foo>& rhs) const
    {
        return lhs->index < rhs->index;
    }
};

and use it: 并使用它:

std::set<std::shared_ptr<Foo>, SharedFooComparator> bar;

You could additionally generalize this to a generic comparator for shared_ptr's: 您还可以将其通用化为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);
    }
};

and then simply make Foo comparable. 然后简单地使Foo具有可比性。

You can provide your own specialization of less<shared_ptr<Foo>> in the std namespace. 您可以在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
      }
   };
}

Then you can form a set<shared_ptr<Foo>> without a comparator. 然后,您可以在没有比较器的情况下形成set<shared_ptr<Foo>> I needed this for a priority_queue<shared_ptr<Foo>> , where I didn't want to use a priority_queue<Foo*, vector<Foo*>, int (*)(const Foo*, const Foo*)> . 我需要一个priority_queue<shared_ptr<Foo>> ,我不想在其中使用priority_queue<Foo*, vector<Foo*>, int (*)(const Foo*, const Foo*)> I am not proud of it, but it works. 我不为此感到骄傲,但它确实有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM