Reputation: 1153
I use approach of vector of vector and would like to change it into array for performance reasons. However I failed at trying to understand, how can I use array (dynamic) and push data in the end of the array, if I do not know how many data are being read during my while loop. Here snippet below. Can you please explain how to perform it on array, as push_back() is only for vector? Would be so much grateful.
std::vector<vector<double>> v1;
while (1)
{
..../* some code, break condition aswell*/
vector<double> tmp;
while ( .../*new data available*/ )
{
...
tmp.push_back(data);
}
v1.push_back(tmp);
}
Upvotes: 0
Views: 1450
Reputation: 31435
If all the inner vectors are always going to be the same size, you probably don't want a vector of vectors but you can still use it.
The inefficiency can come from having to maintain a contiguous buffer and move objects around. If you have a lot of data that you are trying to store in memory you could use std::deque
instead although in your case not all the data will be contiguous, just within each inner vector and the other vector itself.
If you know the size of the data in the inner vectors before you start doing push_back
you can optimise with a reserve()
.
Your slowness, assuming there is any, could be caused by poor algorithms and if you are accessing a lot of data in memory then cache misses. The latter of these is a complex topic but can lead to big improvements in performance.
Upvotes: 2
Reputation: 1087
A std::vector<T>
is a dynamic array. What might speed up your code is this:
std::vector<vector<double>> v1;
while (1)
{
..../* some code, break condition aswell*/
v1.push_back(vector<double>());
while ( .../*new data available*/ )
{
...
v1.back().push_back(data);
}
}
Upvotes: 3