在类中创建多个对象
Create multiple objects in class
我有一个类,我用它来制作链表。总的来说,我想创建多个列表。我的意思是不覆盖前一个。如何做到这一点,而不必为创建类的对象提供新名称。例如,如果我要列出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);
相关文章:
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 具有包含其他对象的类的对象创建顺序
- 为什么我们再次从结构对象创建结构变量?
- 将对象创建为全局/静态对象会崩溃,而本地对象不会崩溃
- 如何创建一个对象创建函数,该函数将由与其关联的名称调用?
- 如何为自定义模板对象创建专门的函数模板
- 对象创建错误的C++矢量
- 如何为Python Swigged C++对象创建和分配回调函数
- 在 C++ 中为 C 样式对象创建一个透明包装类
- 此类模板的对象创建如何工作?
- C++ 中的对象创建类型有什么区别?
- 未知大小的数组作为类成员,用于在运行时(对象创建时间)创建数组的对象
- 如何仅通过父类对象限制对象创建
- 在正确性或良好的代码结构方面,这种动态对象创建看起来如何
- 无法将类对象创建为另一个类的成员
- 如何从现有基类对象创建派生类对象
- 在 DTor 之前删除的静态对象创建的线程?
- C++:定义多个构造函数时的对象创建/销毁序列
- 从对象创建矢量包装器,该对象只允许使用索引访问向量
- 是否可以为CPP中的对象创建一组指针