std :: vector <struct>到const std :: vector <const struct>*

Que*_*est 1 c++ vector

我有私有变量std::vector<some struct>可以我以某种方式将向量传递给函数返回值,但没有"写"访问权限,因此您将无法向其中添加新元素,并且您将无法修改元素(例如const std::vector<some const struct>*,我怎么能这样做?我唯一的想法就是创建一个带有常量指针的新向量.有更好的解决方案吗?

jua*_*nza 5

您不能通过指针或const向量的引用来修改向量的元素.所以以下是安全的:

const std::vector<some_type>* get_pstuff() const { return &the_vector; }
const std::vector<some_type>& get_rstuff() const { return the_vector; }
Run Code Online (Sandbox Code Playgroud)

另一方面,将const_iterators返回到向量的开头和结尾可能更惯用:

std::vector<some_type>::const_iterator cbegin() const { return the_vector.cbegin(); }
std::vector<some_type>::const_iterator cend() const { return the_vector.cend(); }
Run Code Online (Sandbox Code Playgroud)

  • @Lochemage不,你不能. (2认同)