在类中创建多个对象

Create multiple objects in class

本文关键字:对象 创建      更新时间:2023-10-16

我有一个类,我用它来制作链表。总的来说,我想创建多个列表。我的意思是不覆盖前一个。如何做到这一点,而不必为创建类的对象提供新名称。例如,如果我要列出1000个列表,我就不能给它们取1000个不同的名字。我尝试使用对象数组,但我似乎没有得到它的工作。

编辑:抱歉给您带来不便,但我不允许使用矢量。下面是一些代码:

 list **root;
root=new list*[M];
for (int i=0;i<M;i++)
{
    root[i]=NULL;
    root[i]=new list();
}

这是在main中然后我使用这个

 (*root[pos]).addnode(b,a);

如果您创建了一些链表类LinkedList,您可以创建列表的std::vector。然后你可以遍历它们,做任何你想做的事情。

#include <vector>
int main()
{
    std::vector<LinkedList> lists(1000);
    for (auto& list : lists)
    {
        // do something with each list
    }
}

如果你确切地知道你想要制作多少LinkedList对象,并且这个值是固定的,你也可以使用std::array

#include <array>
int main()
{
    std::array<LinkedList, 1000> lists;
    for (auto& list : lists)
    {
        // do something with each list
    }
}

您可以使用vector来存储链表,也可以使用map来使用键访问链表。

// Here you can use a string to find a specific list
std::map<std::string, LinkedList> listMap;
// Then you can add and access list using the [] operator
listMap["Key"];
// Here you have to use an iterator to access the lists
std::vector<LinkedList> listVector(numberOfListsYouPlanToHave);