Pushing a vector into an vector
I have a 2d vector
typedef vector <double> record_t;
typedef vector <record_t> data_t;
data_t data;
So my 2d vector is data here. It has elements like say,
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
Now I want to insert these elements into another 2d vector
std::vector< vector<double> > window;
So what I did was to create an iterator for traversing through the rows of data and pushing it into window like
std::vector< std::vector<double> &g开发者_Go百科t;::iterator data_it;
for (data_it = data.begin() ; data_it != data.end() ; ++data_it){
window.push_back ( *data_it );
// Do something else
}
Can anybody tell me where I'm wrong or suggest a way to do this ? BTW I want to push it just element by element because I want to be able to do something else inside the loop too. i.e. I want to check for a condition and increment the value of the iterator inside. for example, if a condition satisfies then I'll do data_it+=3 or something like that inside the loop.
Thanks
P.S. I asked this question last night and didn't get any response and that's why I'm posting it again.
If what you need is:
to check for a condition and increment the value of the iterator inside. for example, if a condition satisfies then I'll do it+=3 or something like that inside the loop.
Then using a while
loop instead of a for
migth help:
std::vector< std::vector<double> >::iterator data_it = data.begin();
while (data_it != data.end()) {
window.push_back ( *data_it );
if (SatisfiesCondition(*data_it)) {
data_it += 3;
}
else {
++data_it;
}
}
Your code currently copies the data row-by-row, not element-by-element.
For element-wise copying of a 2D array, you need a nested loop, as @AmbiguousX already mentioned.
If you start with an empty 2D array window
, the code should look like this:
for (std::vector< record_t >::iterator i = data.begin(); i != data.end(); i++)
{
std::vector<double> row;
for (std::vector<double>::iterator j = i->begin(); j != i->end(); j++)
{
row.push_back(*j);
// do something else with *j
}
window.push_back(row);
}
精彩评论