Bog*_*dan 2 initialization initializer-list c++11
因此,我想练习使用智能指针的技能。我创建了具有以下构造函数的类(单链列表)模板:
template <class Type>
class list
{
//...
public:
list( std::initializer_list < Type > initlist ) { ... }
//...
};
Run Code Online (Sandbox Code Playgroud)
在主函数中,我想构造初始化器列表并将其作为一件事传递给类构造器(类似这样,我认为这是可能的,但我不知道该怎么做):
typedef int Type;
int main ()
{
//...
size_t count; // to know How many elements initlist will have
std :: initializer_list < Type > initlist;
cout << "Enter, please, count of elements and their values\n";
cin >> count;
Type temp_data;
for (size_t i = 0; i < count; i++)
{
cin >> temp_data; //user input data and program add it to list
initlist.push_back( temp_data );
// it's wrong. But I found no analogue of "push_back" in std :: initializer_list
// I used push_back to explain what I want to do
}
// ... do stuff
// now I want to pass it to the class object
list < Type > mylist ( initlist ); // or mylist = initlist, or mylist{initlist}
}
Run Code Online (Sandbox Code Playgroud)
我可以像下面那样做,但是如果我不知道用户将输入多少个元素,那么我应该怎么做:
list <Type> mylist {1,2,3,4,5,6,7,8};
Run Code Online (Sandbox Code Playgroud)
那么,我该怎么做才能正确编写它?也许有人有一个主意。谢谢。
通常在C ++容器中,既提供std::initializer_list构造函数,又提供采用两个迭代器(任意给定大小)的构造函数,并将该“范围”的内容复制到容器中。
因此,例如,您的班级可能有这样的事情:
template <class Type>
class list {
//...
public:
list(std::initializer_list<Type> initlist) { ... }
template<typename It>
list(It begin, It end) { ... }
//...
};
Run Code Online (Sandbox Code Playgroud)
在标准库std::vector,std::list, std::forward_list,std::deque和其他容器都支持的。
这样做是为了,如果用户在创建容器的那一刻就知道他/她想插入到容器中的元素,则他/她将使用std::initializer_list重载。否则,如果他/她具有其他动态构建的容器,则他只需将元素导入您的容器中即可。
| 归档时间: |
|
| 查看次数: |
1478 次 |
| 最近记录: |