Reputation: 54113
I was wondering if it was faster to have a std::vector<std::vector<double>>
where the nested vector always has 2 elements, or is it faster to have a std::vector<MyPoint>
where MyPoint is defined like:
struct MyPoint {
double Point[2];
};
Thanks
Upvotes: 3
Views: 288
Reputation: 279255
The vector<MyPoint>
is preferable, because MyPoint
is likely:
vector<double>
(you can check this with sizeof
), and/orFor example on my 32bit gcc, std::vector<double>
has size 12, while MyPoint
has size 16, but the vector makes the extra allocation. On a 64bit implementation, MyPoint
will almost certainly be the same size, but std::vector
will probably be bigger.
Also, a vector represents a variable-sized, ordered container using contiguous memory. So it's arguably overkill for a size-2 array, since the use of a vector introduces the possibility that the size might change.
Upvotes: 11
Reputation: 3056
Not only the vector of two elements is slower, it also looks strange to have a dynamic structure to keep always 2 elements (assuming it is not going to change). I would use struct MyPoint { double x, y; };
for convenience.
Upvotes: 1
Reputation: 24988
Do you mean std::vector<MyPoint>
in the second example? This would be considerably better than having a vector within a vector.
Upvotes: 0
Reputation: 347216
I assume in the second example you meant: std::vector<MyPoint>
? Yes that variant would be more efficient. For example you can reserve a large amount of memory easier and you will have to do less allocations overall.
Instead of MyPoint you could also use std::pair<double, double>
.
Upvotes: 5