我可以访问作为const引用的唯一指针吗?

时间:2017-04-12 16:39:46

标签: c++ c++11

我有一组ms_order对象的unique_ptr对象:

std::vector<std::unique_ptr<ms_order>> orders;

我想创建一个私有帮助函数来获取ms_order对象:

const std::unique_ptr<ms_order>& ms_order_collection::get_order(const std::string &id) {
    std::vector<std::unique_ptr<ms_order>>::iterator it =
            std::find(orders.begin(), orders.end(),
                      [&id](const std::unique_ptr<ms_order>& op)
                      { return op->getId() == id; });
    return *it;
}

我收到以下错误:

error: no match for 'operator==' (operand types are 'std::unique_ptr<ms_order>' and 'const ms_order_collection::get_order(const string&)::<lambda(const std::unique_ptr<ms_order>&)>')
  { return *__it == _M_value; }
           ~~~~~~^~~~~~~~~~~

错误对我没有意义。我正在努力做甚么可能吗?如果是这样我做错了什么?

1 个答案:

答案 0 :(得分:5)

您应该使用std::find_if而不是std::find

Test123将给定迭代器范围中的每个元素与std::find进行比较。在您自己的情况下,您提供的值是一个lambda对象,它是一个匿名类型,与value

中的元素类型没有等价关系(或合适的operator ==

orders在每个元素上调用您的仿函数,并返回迭代器位置,如果std::find_if,则返回结束迭代器。