我应该怎么做才能将 data/values/objects 添加到初始化列表,然后将其发送到构造函数?

What should I do to add data/values/objects to an initializer list and later send it to a constructor?

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

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

          //...
    };

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

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};

那么,我应该怎样写才正确呢?也许有人有想法。 谢谢

不存在动态大小 std::initializer_list 这样的东西。 class 应该是轻量级和简单的。

您可以为您的 list class 实施 push_backpush_front 并逐步构建它。

与您当前的想法类似的是构建一个 std::vector 或类似的,然后提供一个构造函数,该构造函数采用迭代器范围从该容器中复制。

通常在 C++ 容器中提供一个 std::initializer_list 构造函数和一个采用两个迭代器(任意给定大小)并将 "range" 的内容复制到容器中的构造函数。

例如,您的 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 和其他容器都支持这些。

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