-3

I have a reference to a vector of pointers, as follows:

std::vector<Object*>& objects;

How can I access Objects from this vector?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Con O'Leary
  • 99
  • 1
  • 10

2 Answers2

1

You can index it with [] as long as you don't try to access an elment outside the the vector... or to be safer, if you need to do something to every element you could use a range based for loop:

for(auto& object : objects) 
   object->someFunction();
vmp
  • 2,370
  • 1
  • 13
  • 17
1

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;
John Bollinger
  • 160,171
  • 8
  • 81
  • 157