C++ 11 - 如何使用带有共享指针向量的priority_queue?

waa*_*919 1 c++ vector priority-queue shared-ptr c++11

我有一个priority queue班级,像这样:

    class Foo
    {
    public:
        //public methods...
    private:
        std::priority_queue<Obj, std::vector<Obj>, object_less> foo_queue;

        //private methods and members...
    }
Run Code Online (Sandbox Code Playgroud)

我一直在使用该emplace()方法在我的内部插入对象priority_queue,如下所示:

void Foo::add( ... ) {
    foo_queue.emplace(var1, var2);
}
Run Code Online (Sandbox Code Playgroud)

这将调用构造函数Obj(var1,var2)并将其插入到priority queue.

但现在,我需要std::vector<Obj>从外面访问.从我的Obj对象.

类似于创建一个Foo object和更改成员的东西,它位于以下对象内priority_queue:

Foo myFoo; // <-- this is where the priority_queue is!

Obj myObj(1); //Creating an object that has some member with value '1'

myFoo.add(myObj); //This will add the object to the priority_queue via emplace (actually it is creating a new object...and not using that one)

myObj.m_member = 2; //HERE WON'T WORK!!! And now I want to change some value on my Obj to '2'. It won't work, because the object that lives inside the priority_queue is different from this one!
Run Code Online (Sandbox Code Playgroud)

所以,我在考虑:

  • 而不是使用该emplace方法,使用push(可能推送不会创建一个新对象)
  • 更改priority_queue为,而不是具有std::vector<Obj>带有共享指针向量的对象的向量,因此我可以访问Obj它位于priority_queuefrom outside ... 内部,如上所示.

题:

你认为这是个好主意吗?我是smart_pointers的新手..我不知道是否有更简单的解决方案.

如何使用带有shared_pointers向量的priority_queue?有人知道我可以遵循一个简单的例子吗?

像这样的东西:

std::priority_queue<std::shared_ptr<Obj>, std::vector<std::shared_ptr<Obj>>, object_less> foo_queue;
Run Code Online (Sandbox Code Playgroud)

然后希望,我可以执行:

Foo myFoo;
Obj myObj(1);
myFoo.add(myObj);
myObj.m_member = 2; //<--Now the m_member should be 2 inside the priority_queue.. is this "possible"?
Run Code Online (Sandbox Code Playgroud)

Sne*_*tel 6

拥有shared_ptrs的优先级队列没有任何问题.你需要注意的一件事是比较.priority_queue当然,需要进行比较,默认使用operator <.但是,在shared_ptrs上,该运算符会比较指针本身而不是指向对象.您需要将自定义比较器传递给优先级队列,该队列对象本身进行操作.幸运的是,您似乎已经在使用自定义比较器,因此如果您忘记这样做,编译器会对您大喊大叫(虽然错误消息可能非常神秘).

另一个警告:如果以一种影响其在优先级队列中的排序的方式修改对象,那么东西就会出错.通过priority_queue接口执行此操作的唯一方法是从队列中删除元素,更改它并重新添加它.