Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL vectors and using the [] operator

Tags:

c++

stl

vector

I'm trying to get the following line to compile, but i'm suffering from pointer confusion:

int test = _s->GetFruitManager()->GetFruits()[2].GetColour();
std::cout << test << std::endl;

where _s is a pointer to S, and GetFruitManager() returns a pointer to a FruitManager object, GetFruits() returns a std::vector<Fruit>* and i then want to be able to use the operator [] to acess a specific Fruit object and call the Fruit's GetColour() method.

I think at some point i need to dereference the vector* returned by GetFruits() but i can't figure out how.

Apologies if this is somewhat convoluted! i'm still quite new to the language, but would appreciate some help clearing this up. I did try to break it down into more digestible steps but was unable to get it to compile either way.

I've actually just decided not to use this code snippet anyway, but it's become a matter of curiosity so i'll still submit the question anyway :)

like image 607
Holly Avatar asked Dec 04 '22 16:12

Holly


2 Answers

You need to do this:

(*(_s->GetFruitManager()->GetFruits()))[2].GetColour();
like image 89
Cthutu Avatar answered Dec 09 '22 15:12

Cthutu


As an alternative to using the [] syntax, you can invoke .at():

int test = _s->GetFruitManager()->GetFruits()->at(2).GetColour();
like image 42
Robᵩ Avatar answered Dec 09 '22 15:12

Robᵩ