Gen*_*ode 0 c++ struct vector object
我想在构建struct. 这样做的原因是我发现这resize()可能非常慢。
这是一些试图做我想做的事情的最小代码,但坏了。
#include <iostream>
#include <vector>
using namespace std;
struct Struct_w_Vector {
~Struct_w_Vector() {} // destructor
int n;
vector<double> h(n, 0.0);
Struct_w_Vector(int n) : n(n) {
// create vector h of size n filled with 0.0 now because resize() takes much more time
} // constructor
};
int main() {
vector<double> h(10, 0.0); // what I would like to make happen inside of the struct
Struct_w_Vector v(10);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
是否有可能设置的大小vector的double名为小号h来是n在建设充满了0的大小(不使用调整大小)?
感谢您的时间。
这将实现您所需要的:
Struct_w_Vector(int n) : n(n), h(n) {}
Run Code Online (Sandbox Code Playgroud)
这个很接近,但在标准 C++ 中不允许使用括号,而且n在这一点上没有初始化:
vector<double> h(n, 0.0);
Run Code Online (Sandbox Code Playgroud)
所以最好放弃它。
请注意,您可能不需要存储n,因为您始终可以使用h.size(). 您也不需要声明析构函数。这让你有
struct Struct_w_Vector {
vector<double> h;
Struct_w_Vector(int n) : h(n) {}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |