Solution 1:
If i have a class like,
class car{ public: int a; string b; bool c;};
i can build a vector of 200 cars:
std::vector<car> allcas;
allcars.resize(200)
at runtime, i just do:
this_car=allcars[102];
then ….
Solution 2:
i have
std::vector<int> a; a.resize(200);
std::vector<string>b; b.resize(200);
std::vector<bool> c; c.resize(200);
this_car_a = a[102];
this_car_b = b[102];
this_car_c = c[102];
Question:
Which one is faster?
Does anyone have an idea? thanks a lot in advance!
A “struct of vectors” has a couple of advantages over a “vector of structs”:
On the other hand, premature optimization is the root of all evil:
So, my recommendation is to use vector-of-structs by default, but keep struct-of-vectors in mind as an alternative (i.e., make sure you can switch later, if you expect sequential/local access patterns and it doesn’t cost much effort up front). Once your program is running, you can profile it to see where the performance-critical sections are, and try out struct-of-vector and vectorized operations where they’ll do the most good.