-
std::vector efficiency
I have a vector<some struct> obj. Question: which is more efficient or are both methods about the same?
Code:
struct mystruct
{
long quantity;
... // other stuff here
};
vector<mystruct> obj;
int i; // assum its already set to a valid number
++obj[i].quantity;
or this
mystruct s& obj[i];
++s.quantity;
-
Do you mean this:
Code:
mystruct& s = obj[i];
It is the same as asking which of these is more efficient:
Code:
int i = 10;
++i;
// or
int& j = i;
++j;
If you have a reason to do the second one like for better clarity, readability, etc, then do it. The extra reference variable shouldn't make a noticable difference. If you don't have a preference, then use the first to avoid the extra variable.
-
>which is more efficient or are both methods about the same?
It shouldn't matter since just about any standard optimization will outweigh the difference between the two examples you gave. But since you didn't ask which you should use, only which is more efficient, I would guess the first because it avoids an initialization operation. I'm guessing only because it's really hard to tell what's faster just by looking at the code. A better way to figure it out is to use a profiler.
Cheers!