[英]Can i construct a linked list with curly braces?
I am fairly new to object oriented C++, and I'm trying to make a constructor for a linked list in this way: 我是面向对象的C ++的新手,我正在尝试以这种方式为链表创建一个构造函数:
Somewhere in the List.h we'd have this: List.h中的某个地方我们有这个:
struct Node
{
int data;
Node *next;
};
and then in the main.cpp, I'd like to be able to construct a list like this: 然后在main.cpp中,我希望能够构建一个这样的列表:
int main()
{
List A({1,2,3,4,5,6});// I want the amount of numbers to indicate the size of
//the list and the numbers to go into each node in order
return 0;
}
So my question is, can i make such a constructor? 所以我的问题是,我可以制作这样的构造函数吗? If so then how?
如果是这样呢? Do i have to use templates do this?
我必须使用模板吗? I tried to find a question like this answered in SO but they all included templates and i haven't learned that yet.
我试图在SO中找到这样的问题,但它们都包含模板,我还没有学到。 If i can make my constructor to do this, is it possible to do it without using templates?
如果我可以让我的构造函数执行此操作,是否可以在不使用模板的情况下执行此操作?
Yes you can do this (using C++11). 是的,你可以这样做(使用C ++ 11)。
You need to define a constructor taking an std::initializer_list<int>
. 您需要定义一个采用
std::initializer_list<int>
的构造std::initializer_list<int>
。 (Yes this is a template, but I will show you how to use it. :-) ) (是的,这是一个模板,但我会告诉你如何使用它。:-))
A possible implementation of an std::intitializer_list<int>
-constructor could look like this: std::intitializer_list<int>
可能实现可能如下所示:
//in class List:
List (std::initializer_list<int> init) {
for (auto v : init)
this->emplace_back(v);
}
where you have to implement emplace_back
yourself as an exercise. 你必须自己实施
emplace_back
作为练习。 emplace_back
should construct a new Node
and append it to the List
. emplace_back
应该构造一个新的Node
并将其附加到List
。 It will be a useful member function (I promise). 它将是一个有用的成员函数(我保证)。
Probably unimportant notice: If emplace_back
does heap allocations, this code might leak. 可能不重要的通知:如果
emplace_back
执行堆分配,则此代码可能会泄漏。 In this case, delegate to a constructor that puts the List
into a valid state, so the destructor can free all the heap-allocated Nodes
. 在这种情况下,委托给将
List
置于有效状态的构造函数,因此析构函数可以释放所有堆分配的Nodes
。 If you do not understand this, it is most likely not too important for your application. 如果您不理解这一点,则很可能对您的应用程序不太重要。
You need a constructor that takes a std::initializer_list
. 你需要一个带有
std::initializer_list
的构造std::initializer_list
。 See an example here: http://en.cppreference.com/w/cpp/utility/initializer_list 请参阅此处的示例: http : //en.cppreference.com/w/cpp/utility/initializer_list
not really. 并不是的。 I believe the declaration of the number list in curly braces will confuse the compiler.
我相信花括号中的数字列表的声明会混淆编译器。 Better to declare an int array and pass it to a constructor that takes an int array and a size variable Consider the following:
最好声明一个int数组并将其传递给一个带有int数组和size变量的构造函数请考虑以下内容:
int aray[] = {5,6,11,22,11};
int size = sizeof(aray)/sizeof(int);
MyList(size,aray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.