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?
如何使用shared_ptr访问值?
2 个解决方案
#1
3
I think something like this:
我觉得这样的事情:
std::string& rear()
{
assert(data.get() != 0 && !data->empty());
return *(*data).rbegin();
};
-
*data
is a vector -
(*data).rbegin()
returns a reverse iterator pointing to the last element -
*(*data).rbegin()
dereferences the iterator, getting its value (a reference)
*数据是一个向量
(* data).rbegin()返回指向最后一个元素的反向迭代器
*(* data).rbegin()取消引用迭代器,获取其值(引用)
#2
3
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
;
};
#1
3
I think something like this:
我觉得这样的事情:
std::string& rear()
{
assert(data.get() != 0 && !data->empty());
return *(*data).rbegin();
};
-
*data
is a vector -
(*data).rbegin()
returns a reverse iterator pointing to the last element -
*(*data).rbegin()
dereferences the iterator, getting its value (a reference)
*数据是一个向量
(* data).rbegin()返回指向最后一个元素的反向迭代器
*(* data).rbegin()取消引用迭代器,获取其值(引用)
#2
3
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
;
};