数组类成员,在运行时长度可动态更改
我正在尝试制作一个网络应用程序。它的类蓝图大致是这样的 -
class Node
{
public:
// member functions
private:
int nodeID;
// other members
};
class NodeNetwork
{
public:
// member functions
private:
Node nodeArray[MAX_NODES];
// other members
};
这里,Node类将处理每个节点,NodeNetwork用于处理完整的网络。
nodeArray
中的实际节点数在运行时可以从 0 到 MAX_NODES 变化,即不一定总是 MAX_NODES
,节点数在运行时可以增加或减少。而且,当程序启动时,数字将始终为0,之后它将开始增加。
我正在使用 Node nodeArray[MAX_NODES];,但我认为这是严重的空间浪费,因为我在运行时并不总是有 MAX_NODES
节点。所以我正在寻找优化它的方法。我希望它以零长度数组开头,但可以根据运行时添加或删除的节点,根据上述约束增加或减少大小。我在互联网上进行了研究,但没有找到任何具体的答案。
我希望有人能帮我解决这个问题,先谢谢了。
I am trying to make a network application. Its class blueprint is roughly like this-
class Node
{
public:
// member functions
private:
int nodeID;
// other members
};
class NodeNetwork
{
public:
// member functions
private:
Node nodeArray[MAX_NODES];
// other members
};
Here, the Node class will deal with each node and the NodeNetwork is used to deal with the complete network.
The actual number of nodes in nodeArray
can vary from 0 to MAX_NODES during runtime, i.e., it may not always be MAX_NODES
, the number of nodes can be increased or decreased during runtime. Moreover, when the program starts the number will always be 0, after that it will start increasing.
I am using Node nodeArray[MAX_NODES];
, but I think it's a serious wastage of space as not always I will have MAX_NODES
nodes at runtime. So I am looking for ways to optimize it. I want it so that it starts with a zero-length array, but the size can be increased or decreased subjected to the above constraints based on the nodes added or removed at runtime. I researched on the internet but did not find any concrete answer.
I hope someone can help me solve this problem, thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以为此目的使用动态数组分配:
..并且在您希望更改元素数量的任何时候:
..因此对于您的情况,您可以编写:
但这对于大型数组来说可能会花费大量时间。
使用
std::vector
: ..so :因此,最好您可以针对您的情况
You can use dynamically array allocation for this purpose:
..and anytime you wish to change the number of elements:
..so for your case you can write:
But this can take a lot of time for huge arrays.
So preferably, you can use
std::vector
:..so for your case:
您可以使用
std::vector
代替大批。也就是说,您可以将数据成员nodeArray
设为std::vector
,如下所示。在上面的 demo 中,我们使用
将元素添加到
成员函数。nodeArray
数据成员中>std::vector::push_back上述程序的输出可以在此处查看:
You can use
std::vector
instead of array. That is, you can make the data membernodeArray
to be astd::vector<Node>
as shown below.In the above demo we have added elements into the
nodeArray
data member by usingstd::vector::push_back
member function.The output of the above program can be seen here: