Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am searching through a vector of unique_ptr's to an object. The object is resolved, for instance, by a user entering a name. Hence a function of the sort:

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"));
}

I would like to reuse this function in the case when adding an object to this vector. Function should call this and in the case of not finding it return something that can be checked by the calling function, instead of throwing an exception. The calling function can throw the exception on checking the return value. My question is what can be returned that calling function can be checked?

like image 709
Jan Swart Avatar asked Dec 20 '25 01:12

Jan Swart


2 Answers

Just return a pointer:

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;
}
like image 79
James Kanze Avatar answered Dec 22 '25 16:12

James Kanze


You can also use something like boost::optional here:

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;
}

Usage:

const auto val = objectForName("bla1");
if (val) std::cout << "ok: " << val.get()->getName();
else std::cout << "none";
like image 38
Pavel Davydov Avatar answered Dec 22 '25 15:12

Pavel Davydov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!