Search code examples
c++c++11stdvectorinitializer-list

Initializer list for vector of objects


I have the following sample code. Is it possible to initialize a list of objects without specifying the "Test" in the vector of objects, or is this the best way? Thanks.

class Test {
public:
    Test(const std::initializer_list<int> list) : m_(list) {

    }

private:
    std::vector<int> m_;
};

int main(int argc, char **argv) {
    std::vector<Test> v = { Test({1, 2, 3}), Test({1, 2, 4}) };


}

Solution

  • The following works:

    std::vector<Test> v = {{1, 2, 3}, {1, 2, 4}};
    

    But I'm not sure if this is what you meant.