简体   繁体   中英

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


}

The following works:

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

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

The following are all valid methods to initialize a vector<Test> .

 std::vector<Test> v1 = { Test({1, 2, 3}), Test({1, 2, 4}) };
 std::vector<Test> v2{Test({1, 2, 3}), Test({1, 2, 4}) };

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM