通过 unique_ptr 的向量搜索的查找函数的返回值
Return value of a find function searching through a vector of unique_ptr's
我正在搜索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";
相关文章:
- 递归ASMVisitor 和查找函数调用站点
- C++ - 查找函数无法在子字符串上执行
- 查找函数是否为常量
- GDB 如何查找函数退出的位置
- 查找函数在unordered_map中的工作方式是搜索键值
- 在 C++ <algorithm>中查找函数
- 错误:二进制表达式的操作数无效(映射使用查找函数错误)
- 哪个查找规则阻止编译器查找函数
- 在C++中查找函数的调用方(Visual Studio)
- 关于获取行和字符串查找函数的问题
- 查找函数在失败结果中应该返回什么
- 如何使用调用和别名指令在 llvm 字节码中查找函数名称
- std::字符串类查找函数不返回预期结果.我可能用错了
- 在成对向量中查找函数时出错
- 从堆栈指针中查找函数参数值
- 如何定义查找函数
- 如何查找函数是否可重入
- 在c++中查找函数
- GNU g++ 4.9.2 查找函数调用的编译错误
- 使用GDB查找函数对应的内存地址/调试