C STL矢量半恒定
C++ STL vector semi-constant
本文关键字:STL 更新时间:2023-10-16
我想从具有以下属性的方法中返回std::vector
:接收器(用户)将能够在向量中编辑元素,但不要更改向量本身(resize,resize,resize,resize of删除,添加等)
- 如果我返回
std::vector<T>&
,则接收器将能够调整大小,向其添加元素等。 - 如果我返回
std::vector<T> const&
(我声明了吗?),他们将无法更改元素。 - 如果我返回
std::vector<T>
,它将是一个全新的向量,而对元素的更改将不会在原始的。
有什么办法做到这一点吗?也许是参考文献的否决权,返回为const(std::vector<T&> const
)?还有这样的东西吗?如果有的话,它可以隐式转换我的std::vector<T>
吗?
由于您似乎可以通过参考返回向量,因此可以将迭代器返回到该向量的开始和结尾。使用迭代器,用户可以编辑任何矢量成员,但不能在没有矢量本身的情况下添加或删除它们。
您还可以提供一个提供随机访问索引的函数,可能是 operator[]
。
如果您不想要向量的属性,请不要返回向量。设计一个具有所需属性的类。如果合适,请使用向量实现它。向量是一种工具,而不是目的。
// vector of pointers to elements by value
std::vector<T*>
// reference to const vector of pointers to elements
std::vector<T*> const&
// shared pointer of to const vector of pointers to elements
std::shared_ptr<std::vector<T*> const>
// vector of shared pointers to elements by value
std::vector<std::shared_ptr<T> >
// reference to const vector of shared pointers to elements
std::vector<std::shared_ptr<T> > const&
// shared pointer of to const vector of shared pointers to elements
std::shared_ptr<std::vector<std::shared_ptr<T> > const>
相关文章:
- 没有找到相关文章