在多维向量中插入元素 [英] Inserting elements in multidimensional Vector
问题描述
vector< vector< int>> sort_a;
vector< int> v2;
vector< int> v3;
for(int i = 0; i <4; ++ i){
v2.push_back(i);
for(int j = 0; j <4; ++ j){
v3.push_back(j);
sort_a.push_back(v2);
sort_a.push_back(v3);
}
}
向量sort_a应该是一个4x4数组,而是输出为31x1,有很多空元素,如何在多维向量中插入元素?
认为它是一个多维向量,认为它是向量的向量。
int n = 4;
std :: vector< std :: vector< int>> vec(n,std :: vector< int>(n));
//通过外向量vec循环
for(int i = 0; i //循环通过内向量vec [i]
for(int j = 0; j (vec [i])[j] = i * n +
}
}
我在
b
如果你想通过 push_back
填充你的向量,你可以在内循环中创建一个临时向量,填充它,然后push_back它到您的向量:
for(int i = 0; i std :: vector ; int> temp_vec;
for(int j = 0; j< n; j ++){
temp_vec.push_back(j);
}
vec.push_back(temp_vec);
}
但是, push_back
调用导致更慢的代码,因为不仅你需要重新分配你的向量所有的时间,而且你必须创建一个临时和复制它。
vector<vector<int>> sort_a;
vector<int> v2;
vector<int> v3;
for (int i=0; i<4; ++i) {
v2.push_back(i);
for (int j=0; j<4; ++j) {
v3.push_back(j);
sort_a.push_back(v2);
sort_a.push_back(v3);
}
}
Vector sort_a should be a 4x4 array, instead the output is 31x1 with lots of empty elements, how do i insert elements in a multidimensional vector ?
Don't think of it as a multidimentional vector, think of it as a vector of vectors.
int n = 4;
std::vector<std::vector<int>> vec(n, std::vector<int>(n));
// looping through outer vector vec
for (int i = 0; i < n; i++) {
// looping through inner vector vec[i]
for (int j = 0; j < n; j++) {
(vec[i])[j] = i*n + j;
}
}
I included parentheses in (vec[i])[j]
just for understanding.
Edit:
If you want to fill your vector via push_back
, you can create a temporary vector in the inner loop, fill it, and then push_back it to your vector:
for (int i = 0; i < n; i++) {
std::vector<int> temp_vec;
for (int j = 0; j < n; j++) {
temp_vec.push_back(j);
}
vec.push_back(temp_vec);
}
However, push_back
calls result in slower code, since not only you need to reallocate your vector all the time, but also you have to create a temporary and copy it.
这篇关于在多维向量中插入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!