通过 unique_ptr 的向量搜索的查找函数的返回值

Return value of a find function searching through a vector of unique_ptr's

本文关键字:查找 函数 返回值 向量搜索 通过 ptr unique      更新时间:2023-10-16

我正在搜索unique_ptr的向量到对象。例如,通过用户输入名称来解析对象。因此有这样一个函数:

std::unique_ptr<obj> const& objectForName(std::string name) {
    std::vector<std::unique_ptr<obj>>::iterator it;
    it = std::find_if(objVec.begin(), objVec.end(), [name](const std::unique_ptr<obj>& object) -> bool {return object->getName() == name; });
    if (it != objVec.end())
      return *it;
    else
      throw(Some_Exception("Exception message"));
}

我想在向这个向量添加对象的情况下重用这个函数。函数应该调用this,并且在没有找到它的情况下返回可以由调用函数检查的东西,而不是抛出异常。调用函数可以在检查返回值时抛出异常。我的问题是什么可以返回调用函数可以检查?

返回一个指针:

obj const* objectForName( std::string const& name )
{
    std::vector<std::unique_ptr<obj>>::iterator results
            = std::find_if(
                objVec.begin(),
                objVec.end(),
                [&]( std::unique_ptr<obj> const& object ) {
                            return object->getName == name; } );
    return results != objVec.end()
        ? results->get()
        : nullptr;
}

您也可以使用这里的boost::optional:

boost::optional<std::unique_ptr<obj> const&> objectForName(std::string name);
    std::vector<std::unique_ptr<obj>>::iterator it;
    it = std::find_if(objVec.begin(), objVec.end(), [name](const std::unique_ptr<obj>& object) -> bool {return object->getName() == name; });
    if (it != objVec.end())
      return *it;
    else
      return boost::none;
}

用法:

const auto val = objectForName("bla1");
if (val) std::cout << "ok: " << val.get()->getName();
else std::cout << "none";