如何使用构造函数初始值设定项列表中的n个元素初始化std :: vector <std :: time_t>

我试图像这样在构造函数初始化列表中初始化向量:

Foo::Foo()
    : vec{42}
{
    //  ...
}

该向量声明为:

std::vector<std::time_t> vec;

Problem is that std::time_t is numeric type also, so instead of creating vector with 42 elements as I would like, it creates one element with stored value '42'.

问题:有没有一种方法可以在构造函数初始值设定项列表中使用大小初始化此类向量?

评论
  • 陌若惜
    陌若惜 回复

    When initialized with braced-init-list, the constructor of std::vector taking std::initializer_list is preferred; for vec{42} it would initialize vec containing 1 element with value 42.

    您可以更改为括号初始值设定项。

    Foo::Foo()
        : vec(42)
    {
        //  ...
    }