[英]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. 所以我的2d向量是这里的数据 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 现在我想将这些元素插入另一个2D向量中
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> >::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.
顺便说一句,我想逐个元素地推送它,因为我也希望能够在循环内做其他事情。 ie 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.
例如,如果条件满足,那么我将在循环内执行data_it + = 3或类似的操作。
Thanks 谢谢
PS I asked this question last night and didn't get any response and that's why I'm posting it again. PS我昨晚问了这个问题,但没有得到任何回应,这就是为什么我再次发布它。
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.
例如,如果条件满足,那么我将在循环内执行+ = 3或类似的操作。
Then using a while
loop instead of a for
migth help: 然后使用
while
循环而不是for
migth帮助:
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. 对于2D数组的逐元素复制,您需要一个嵌套循环,如@AmbiguousX所述。 If you start with an empty 2D array
window
, the code should look like this: 如果从一个空的2D数组
window
,则代码应如下所示:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.