[英]Reserving elements in a 3D vector c++
I have a 3d container:我有一个 3d 容器:
std::vector<int, std::vector<std::vector<double>>> myVec;
that I want to have the dimensions [n+1][3*(n+10)+1][16*(n+10)+1].我想要尺寸 [n+1][3*(n+10)+1][16*(n+10)+1]。 I want to reserve this space in the vector quickly and without too many other spaghetti functions so I can emulate a dynamic 3D array.
我想快速保留向量中的这个空间,并且没有太多其他意大利面条函数,这样我就可以模拟动态 3D 数组。 How would I do this?
我该怎么做?
Reserve or size?预定还是尺寸?
http://www.cplusplus.com/reference/vector/vector/reserve/ http://www.cplusplus.com/reference/vector/vector/resize/ http://www.cplusplus.com/reference/vector/vector/reserve/ http://www.cplusplus.com/reference/vector/vector/resize/
Demonstration of resize using constructor:使用构造函数调整大小的演示:
#include <iostream>
#include <vector>
using namespace std;
template <class T>
void printSize(T v) {
cout<<v.size()<<endl;
}
int main(){
int n = 1;//Initial n value;
int d1 = n+1, d2 = 3+(n+10)+1, d3 = 16*(n+10)+1;
vector<vector<vector<int>>> i3D(d1,vector<vector<int>>(d2,vector<int>(d3)));
//i3D.resize(d1,vector<vector<int>>(d2,vector<int>(d3)));
printSize(i3D);
printSize(i3D[0]);
printSize(i3D[0][0]);
return 0;
}
In my example, I've resized using the constructor.在我的示例中,我使用构造函数调整了大小。 You can do the same using the resize method.
您可以使用调整大小方法执行相同操作。
Reserve on the other hand will require (that I know of) the use of loops and reserve memory per array (all).另一方面,保留将需要(据我所知)使用循环并为每个数组(全部)保留内存。
Considered it to be a question of resize, because you indicated preset sizes for x, y, and z dimensions.将其视为调整大小的问题,因为您指定了 x、y 和 z 维度的预设大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.