Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning value from shared pointer vector string

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?

like image 907
Goku Avatar asked Jul 28 '26 19:07

Goku


1 Answers

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
        ;
};
like image 91
Abhijit Avatar answered Jul 30 '26 08:07

Abhijit



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!