C++ 在多维向量中插入元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13936733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inserting elements in multidimensional Vector
提问by Gambit King
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 ?
向量 sort_a 应该是一个 4x4 数组,而不是输出是 31x1 有很多空元素,我如何在多维向量中插入元素?
回答by prazuber
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.
我包括括号(vec[i])[j]
只是为了理解。
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:
如果你想通过 填充你的向量push_back
,你可以在内部循环中创建一个临时向量,填充它,然后将它 push_back 到你的向量:
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.
但是,push_back
调用会导致代码变慢,因为您不仅需要一直重新分配向量,而且还必须创建一个临时对象并复制它。
回答by andre
a vector<vector<int>>
is not the best implementation for a multidimensional storage. The following implantation works for me.
avector<vector<int>>
不是多维存储的最佳实现。以下植入对我有用。
template<typename T>
class array_2d {
std::size_t data;
std::size_t col_max;
std::size_t row_max;
std::vector<T> a;
public:
array_2d(std::size_t col, std::size_t row)
: data(col*row), col_max(col), row_max(row), a(data)
{}
T& operator()(std::size_t col, std::size_t row) {
assert(col_max > col && row_max > row)
return a[col_max*col + row];
}
};
use case:
用例:
array_2d<int> a(2,2);
a(0,0) = 1;
cout << a(0,0) << endl;
This solution is similar to the one described here.
此解决方案类似于此处描述的解决方案。