首页 > 解决方案 > 从指针向量的引用访问元素

问题描述

我有一个指针向量的引用,如下所示:

std::vector<Object*>& objects;

如何从此向量访问对象?

标签: c++pointersvectordereference

解决方案


That objects is a reference has no direct bearing on the question -- you use a reference in exactly the same way you use a simple identifier for the same object.

Thus, you can select an individual element of the vector by any of the normal means, such as by index, by iterator, or whatever. The result is of the vector's element type, which is Object *:

Object *o = objects[42];

You can access the object to which o points via the dereference operator (unary *). Alternatively, you can use the indirect access operator (->) to access its methods and fields:

(*o).do_something();
int i = o->an_int;

推荐阅读