我正在通过一个对象的 unique_ptr vector 进行搜索。例如,通过用户输入名称来解析对象。因此有这样一个函数:
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"));
}
我想在将对象添加到此 vector 时重用此函数。函数应该调用它并且在找不到它的情况下返回一些可以被调用函数检查的东西,而不是抛出异常。调用函数可以在检查返回值时抛出异常。我的问题是可以返回什么来检查调用函数?
最佳答案
只返回一个指针:
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;
}
关于c++ - 通过 unique_ptr vector 搜索的查找函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24200135/