I'm trying to implement a return method for a class I want to use smart pointers. I have:
std::shared_ptr<std::vector<std::string>> data;
I want to access its last value with this function:
std::string& rear()
{
};
How do I access values with the shared_ptr?
SImply return the last element from the array after dereferencing the pointer. The member function std::vector::back would return the element from the end of the vector which is also the last element.
It is worth noting, that smart pointers are pointer wrappers, which generally supports the operations that you would have done on C pointers, which includes dereferencing * and member access via dereferencing ->.
std::string& rear()
{
if (data && ! data.empty ())
return data->back();
else
// Your Error Handling Should Go Here
;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With