I have a quick (and possibly stupid) question, but I couldn't find an answer online:
When I pass a struct by reference, I can nicely and cleanly access its fields via MyArray->Field1
, MyArray->Field2
etc.
Is there a similar way to do this for the elements of a std::vector
? The only way to do this I know, is something like MyVector[0][0]
, MyVector[0][1]
etc. or maybe do something like std::vector<double> MyVector2 = *MyVector;
and then MyVector2[0, 1, 2...] = 1.0...
Edit: Wow, was Stackoverflow quick closing my question...
I think, I got passing by reference and passing by pointer confused. I'm not sure, what the better solution in my case is: Basically I have a class where I set a std::vector*
to an "external" std::vector
. It uses this vector a lot of times, so I don't want to copy it all the time for performance reasons (and also the class changes it). Passing it by pointer, as mentioned above, I have to write something like MyVector[0][0] = 3;
and while this works perfectly, it just doesn't look very nice.
The better way of writing this, according to wohlstads answer (thank you for the good explanation) would be (*MyVector)[0] = 3;
.
Passing a std::vector
by refernce allows you to access its public members, e.g.:
void f(std::vector<int> & v)
{
v.resize(1);
v[0] = 3;
}
However, the syntax you used your question actually looks like passing by pointer. You can do that as well with a std::vector
but in C++ we usually prefer to pass by reference. If you have a good reason to pass by pointer instead of a reference, you can do it like that:
void f(std::vector<int> * pV)
{
pV->resize(1);
(*pV)[0] = 3;
}
The brackets around *pV
are necessary because operator []
has precedence over the dereferencing operator (*
); without those, *pV[0]
will be interpreted as *(pV[0])
.