Vector of unique pointers:通过指针找到一个元素然后将其旋转到向量的前面

Vector of unique pointers: Finding and then rotating an element to the front of a vector by pointer

假设我有一个 std::vector 个指向对象的唯一指针。

#include <memory>

struct MyObject {

};

std::vector<std::unique_ptr<MyObject> myObjects;

现在假设 vector 填充了一些对象,我想将一个特定的指针旋转到前面。我尝试像这样使用 find_if 函数来找到一个枢轴:

#include <algorithm>

void rotate_to_front(MyObject * myobject){
     auto pivot = std::find_if(std::begin(myObjects), std::end(myObjects), [myObject](const MyObject & memberObject){
          return myObject == memberObject;
     });
}

但是 clang 抛出 deduced conflicting types for parameter 'Element'.

找到我的支点后,我想用std::rotate把它移到前面。

std::rotate(std::begin(myObjects), pivot, pivot + 1);

备注:

  1. 有没有办法用 std::find 而不是 std::find_if 来做到这一点?我也无法让它工作。

为了std::find_if()编译,lambda的参数必须匹配std::vector中的对象类型,即std::unique_ptr<MyObject>而不是MyObject,或者可以隐式转换到参数类型,这在这种情况下是不可能的。所以,正确的方法是:

 auto pivot = std::find_if(std::begin(myObjects), std::end(myObjects), 
      [myObject](const std::unique_ptr<MyObject> & memberObject){
           return myObject == memberObject.get();
      });

Is there a way to do this with std::find instead of std::find_if?

为此,std::unique_ptr 必须提供一个 operator== 来比较原始指针,但事实并非如此,所以不,你必须自己提供一个谓词。