数组类成员,在运行时长度可动态更改

发布于 2025-01-13 21:25:05 字数 674 浏览 3 评论 0原文

我正在尝试制作一个网络应用程序。它的类蓝图大致是这样的 -

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

够钟 2025-01-20 21:25:05

您可以为此目的使用动态数组分配:

int* arr = new int[5];

..并且在您希望更改元素数量的任何时候:

int size = 5;
int* arr = new int[size] {};

int* new_arr = new int[size + 1];
for (int i = 0; i < size; i++)
{
    new_arr[i] = arr[i];
}
delete[] arr;
arr = new_arr;

// Now arr has a storage capacity of 6 elements

..因此对于您的情况,您可以编写:

Node* nodeArray = nullptr; // nullptr == null pointer

但这对于大型数组来说可能会花费大量时间。

使用 std::vector: ..so :

#include <iostream>
#include <vector>

int main() 
{
    std::vector<int> vec{ 1, 2, 3, 4, 5 };
    vec.push_back(6); //Insert a new element

    std::cout << vec[0]; // Accessing an element is the same as an array
}

因此,最好您可以针对您的情况

// {} is just for initialization, not exactly mandatory
std::vector<Node> nodeArray{};

You can use dynamically array allocation for this purpose:

int* arr = new int[5];

..and anytime you wish to change the number of elements:

int size = 5;
int* arr = new int[size] {};

int* new_arr = new int[size + 1];
for (int i = 0; i < size; i++)
{
    new_arr[i] = arr[i];
}
delete[] arr;
arr = new_arr;

// Now arr has a storage capacity of 6 elements

..so for your case you can write:

Node* nodeArray = nullptr; // nullptr == null pointer

But this can take a lot of time for huge arrays.

So preferably, you can use std::vector:

#include <iostream>
#include <vector>

int main() 
{
    std::vector<int> vec{ 1, 2, 3, 4, 5 };
    vec.push_back(6); //Insert a new element

    std::cout << vec[0]; // Accessing an element is the same as an array
}

..so for your case:

// {} is just for initialization, not exactly mandatory
std::vector<Node> nodeArray{};
囍孤女 2025-01-20 21:25:05

您可以使用 std::vector 代替大批。也就是说,您可以将数据成员 nodeArray 设为std::vector,如下所示。

#include <iostream>
#include<vector>
class Node
{
    public:
       //constructor for initializing nodeID data member 
       Node(int pnodeID): nodeID(pnodeID)
       {
           
       }
       //getter for nodeId
       int getId() const 
       {
           return nodeID;
       }
    private:
       //always initialize built in type in local/block scope so that they don't have indeterminate value
       int nodeID = 0; 
    // other members
};

class NodeNetwork
{
    public:
    
        // member function to add Node 
        void addNode(const Node& n)
        {
            nodeArray.push_back(n);
        }
        //member function to print out the current nodes 
        void display() const
        {
            std::cout<<"Network has the following nodes: "<<std::endl;
            for(const Node& elem: nodeArray)
            {
                std::cout<<elem.getId()<<std::endl;
                
            }
        }
    private:
        std::vector<Node> nodeArray; //used std::vector instead of array
    // other members
};
int main()
{
    //create Node objects 
    Node node1{1};
    Node node2{2};
    Node node3{3};
    
    NodeNetwork network1;
    
    //add node1 into the network1's nodeArray data member 
    network1.addNode(node1);
    
    //add node2 into the network1's nodeArray data member 
    network1.addNode(node2);

    //display all nodes into network1 
    network1.display();
    return 0;
}

在上面的 demo 中,我们使用 将元素添加到 nodeArray 数据成员中>std::vector::push_back 成员函数。

上述程序的输出可以在此处查看:

Network has the following nodes: 
1
2

You can use std::vector instead of array. That is, you can make the data member nodeArray to be a std::vector<Node> as shown below.

#include <iostream>
#include<vector>
class Node
{
    public:
       //constructor for initializing nodeID data member 
       Node(int pnodeID): nodeID(pnodeID)
       {
           
       }
       //getter for nodeId
       int getId() const 
       {
           return nodeID;
       }
    private:
       //always initialize built in type in local/block scope so that they don't have indeterminate value
       int nodeID = 0; 
    // other members
};

class NodeNetwork
{
    public:
    
        // member function to add Node 
        void addNode(const Node& n)
        {
            nodeArray.push_back(n);
        }
        //member function to print out the current nodes 
        void display() const
        {
            std::cout<<"Network has the following nodes: "<<std::endl;
            for(const Node& elem: nodeArray)
            {
                std::cout<<elem.getId()<<std::endl;
                
            }
        }
    private:
        std::vector<Node> nodeArray; //used std::vector instead of array
    // other members
};
int main()
{
    //create Node objects 
    Node node1{1};
    Node node2{2};
    Node node3{3};
    
    NodeNetwork network1;
    
    //add node1 into the network1's nodeArray data member 
    network1.addNode(node1);
    
    //add node2 into the network1's nodeArray data member 
    network1.addNode(node2);

    //display all nodes into network1 
    network1.display();
    return 0;
}

In the above demo we have added elements into the nodeArray data member by using std::vector::push_back member function.

The output of the above program can be seen here:

Network has the following nodes: 
1
2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文