Jan*_*art 3 c++ iterator vector unique-ptr c++11
我正在搜索对象的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"));
}
Run Code Online (Sandbox Code Playgroud)
我想在向此向量添加对象的情况下重用此函数.函数应调用此函数,并且在未找到它的情况下返回可由调用函数检查的内容,而不是抛出异常.调用函数可以在检查返回值时抛出异常.我的问题是可以返回什么可以检查调用函数?
只需返回一个指针:
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;
}
Run Code Online (Sandbox Code Playgroud)