Passing A std::vector as a Pointer to a Function

Started by
2 comments, last by popsoftheyear 9 years, 6 months ago

Hi.

I have a std::vector<obj> data; That is Passed to a function like this FunctionName(std::vector<obj> *data);

Then in the function How should I use std::vector data.

Like This

data[0][elementinvector].doobjfunction(); ///Is this valid to use.

or should I use.

(*data)[elementinvector].doobjfunction();

Are they both doing the same thing just wondering.

Advertisement

Pass it by reference instead and forget about pointers and dereferencing them.

FunctionName(std::vector<obj> &data);
In general I'd recommend to use a reference, but if you actually do need a pointer (e.g. because you need it to be nullable) then you want to explicitly dereference the pointer using the * or -> operators, e.g.

(*data)[index];
data->operator[](index);
data->at(index); // not quite the same as at() will bounds check, operator[] does not
Treating pointers as arrays should be discouraged. It's totally legal and the most correct thing to do in many circumstances, but stylistically it's best to only use pointers as arrays if they're actually meant to be arrays. e.g. data[0] should only be used if data[x] is expected to at some point be legal.

Sean Middleditch – Game Systems Engineer – Join my team!

The previous answers are the correct ones. However,


data[0][elementinvector].doobjfunction(); ///Is this valid to use.

is valid and would work, to answer your question. It would be a really poor idea though, and would confuse anyone that ever looked at your code, because it misleads you to believe there is potential for multiple "std::vector<obj>"s in "data".

This topic is closed to new replies.

Advertisement