[英]Allocating an array in a struct in C++
I am trying to allocate an array of structs within a struct.我正在尝试在结构中分配一个结构数组。 Here is my code:
这是我的代码:
struct t_nd {
double stuff;
};
struct t_nwork {
struct t_nd *nds;
};
struct t_nwork net;
// need to allocate the nds array to be of size 10
tried this but failed:试过这个但失败了:
t_nd* net.nds = new t_nd[10];
someone said try a vector, so I tried:有人说试试向量,所以我试了:
vector<t_node> net.nodes(10);
but yet again failed dismally.但又一次惨败。
someone said try a vector, so I tried:... but failed
有人说尝试向量,所以我尝试了:...但失败了
You can use vector as shown below.您可以使用矢量,如下所示。 In the shown program, we have a data member called
nds
of type vector<t_nd>
.在所示程序中,我们有一个名为
nds
的数据成员,类型为vector<t_nd>
。 Also, we have a constructor that has a parameter of type std::size_t
.此外,我们有一个构造函数,其参数类型为
std::size_t
。
struct t_nd {
double stuff;
};
struct t_nwork {
//data member of type std::vector<t_nd>
std::vector<t_nd> nds;
//constructor to set size of vector
t_nwork(std::size_t psize): nds(psize)
{
}
};
int main()
{
//create object of type t_nwork whose nds have size 10
t_nwork net(10);
}
Here we don't have any constructor to set the size of the vector.这里我们没有任何构造函数来设置向量的大小。
struct t_nd {
double stuff;
};
struct t_nwork {
//data member of type std::vector<t_nd>
std::vector<t_nd> nds;
};
//create object of type t_nwork whose nds have size 10
t_nwork net{std::vector<t_nd>(10)};
This is the solution:这是解决方案:
#include <iostream>
struct t_nd {
double stuff;
};
struct t_nwork {
t_nd* nds;
};
int main() {
t_nwork net;
net.nds = new t_nd[100];
// ...
delete[] net.nds;
}
This is the solution using vector:这是使用向量的解决方案:
#include <iostream>
#include <vector>
struct t_nd {
double stuff;
};
struct t_nwork {
std::vector<t_nd> nds;
};
int main() {
t_nwork net;
net.nds.resize(10);
net.nds[1];
}
#include <iostream>
struct xyz {
int val;
};
struct abc {
struct xyz *xyzPtr;
};
int main() {
struct abc myAbc;
myAbc.xyzPtr = new xyz[10];
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.