[英]Returning value from shared pointer vector string
I'm trying to implement a return method for a class I want to use smart pointers. 我正在尝试为要使用智能指针的类实现return方法。 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? 如何使用shared_ptr访问值?
I think something like this: 我认为是这样的:
std::string& rear()
{
assert(data.get() != 0 && !data->empty());
return *(*data).rbegin();
};
*data
is a vector *data
是向量 (*data).rbegin()
returns a reverse iterator pointing to the last element (*data).rbegin()
返回指向最后一个元素的反向迭代器 *(*data).rbegin()
dereferences the iterator, getting its value (a reference) *(*data).rbegin()
取消引用迭代器,获取其值(一个引用) 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. 成员函数std :: vector :: back将从向量的末尾返回元素,这也是最后一个元素。
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 ->
. 值得注意的是,智能指针是指针包装器,通常支持对C指针所做的操作,包括对*
进行反引用和通过反引用->
成员访问。
std::string& rear()
{
if (data && ! data.empty ())
return data->back();
else
// Your Error Handling Should Go Here
;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.