c++11 - 我应该怎么做才能将数据/值/对象添加到初始化列表,然后将其发送到构造函数?

标签 c++11 initialization initializer-list

所以我想练习使用智能指针的技能。我创建了一个类模板(单链表),其构造函数如下:

template <class Type> 
class list
  {
          //...
   public:
          list( std::initializer_list < Type > initlist ) { ... }

          //...
    };

在主函数中,我想构造初始化列表并将其作为一件事传递给类构造函数(像这样,我认为有可能,但我不知道该怎么做):

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}

}

我可以像下面那样做,但如果我不知道用户将输入多少和哪些元素,那么我应该做什么:

list <Type> mylist {1,2,3,4,5,6,7,8};

那么,我应该怎么做才能正确编写它?也许有人有一个想法。 谢谢。

最佳答案

通常在 C++ 中,容器同时提供一个 std::initializer_list 构造函数和一个构造函数,该构造函数接受两个迭代器(任何给定大小)并将该“范围”的内容复制到容器中。

例如,您的类(class)可能有这样的内容:

template <class Type> 
class list {
    //...
public:
    list(std::initializer_list<Type> initlist) { ... }

    template<typename It>
    list(It begin, It end) { ... }

    //...
};

在标准库中std::vectorstd::liststd::forward_liststd::deque 和其他容器都支持这些。

这样做是为了如果用户在创建容器时知道他/她想要插入到容器中的元素,他/她会使用 std::initializer_list 重载。否则,如果他/她有其他动态构建的容器,他可以只导入容器中的元素。

关于c++11 - 我应该怎么做才能将数据/值/对象添加到初始化列表,然后将其发送到构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33105290/

相关文章:

c++ - 如何对 std::shared_ptr<Widget> 对象的容器进行排序?

c++ - 没有可用于带有初始值设定项的静态常量成员的定义?

objective-c - 子类化时访问属性

java - 为什么实例初始化 block 在构造函数之前执行

c++ - 逐字段构造函数生成的规则是什么?

c++ - 围绕标量初始值设定项错误的大括号

c++ - lambda 的捕获变量被重置

c++ - 为什么要调用移动构造函数?

iPhone 使用附加数据初始化 UIViewController

c++ - 在constexpr上下文中验证std::initializer_list