It seems it's not possible to store the same item in *two* different vectors, right?
The way I tested this was pushing the item to vector1, then to vector2, then getting pointers to each and comparing them: the addresses are different.
Does this make sense?
Since the addresses were different I assume one is a copy.
-
ps: where do you leave feedback for the site admin?
Minor CSS issue: when logging in with a wrong password the popup error response has white text on white background, which probably isn't intended.
So vector2 would have to hold pointers, like this:
1 2
vector<Item> vector1;
vector<Item*> vector2;
When I access/modify items via vector2 I'd need a pointer to a pointer, right?
Like this:
1 2
Item **item = &vector2[i];
(*item)->doStuff();
That seems complicated.
Alternatively, this would create a copy of the pointer, right?
1 2
Item *item = vector2[i];
item->doStuff();
What's an efficient and sensible way of doing this?
I'll need to do these operations a few thousand times in a loop.
Not talking about premature optimisation, just doing things in a way that's not too wasteful.
Do you really need an extra level of indirection here?
vector2[i] is a pointer. No need to create a pointer to it.
Does not help if vector2 pointer is invalidated (see below).
1 2
Item *item = vector2[i];
item->doStuff();
Alternatively, this would create a copy of the pointer, right?
Yes. A copy of the pointer is created. That shouldn't be a problem, but that depends on how long you keep it around.
Keep in mind that if you're adding items to vector1 after you create vector2, vector1 could get reallocated thereby invalidating any pointers stored in vector2.
The variable is temporary, only needed in the loop.
So copies of the pointers is actually the better solution, or is there another alternative I've overlooked?
Btw, is there any difference between creating the var inside the loop versus creating it before and then reassigning it on each iteration? I mean
1 2
for(...)
int * ptr = vector2[i];
versus
1 2 3
int * ptr;
for(...)
ptr = vector2[i];
I'm guessing that's optimised by the compiler anyway, isn't it?
>Do you really need an extra level of indirection here?
No, I just assumed it would be more efficient.
> Keep in mind that if you're adding items ...
Thanks for the heads-up! However vector1 never changes. Only vector2, it'll hold different subsets of vector1 for different states of the app.
No technical difference. As far as the compiler is concerned, they're both an address or an address of an address in the case of a double pointer or a reference to a pointer.
Coming from a heavy C background, pointers to pointers (and to pointers, etc) is intuitive. References to pointers is certainly the preferred C++ idiom. I'll always use a reference when passing a struct or class around, but for me, a pointer to a pointer is clearer rather than mixing references and pointers. Others may have different preferences.