What is the easiest way to initialize a std::vector with hardcoded elements?

后端 未结 29 3048
终归单人心
终归单人心 2020-11-22 05:07

I can create an array and initialize it like this:

int a[] = {10, 20, 30};

How do I create a std::vector and initialize it sim

29条回答
  •  遇见更好的自我
    2020-11-22 05:35

    Related, you can use the following if you want to have a vector completely ready to go in a quick statement (e.g. immediately passing to another function):

    #define VECTOR(first,...) \
       ([](){ \
       static const decltype(first) arr[] = { first,__VA_ARGS__ }; \
       std::vector ret(arr, arr + sizeof(arr) / sizeof(*arr)); \
       return ret;})()
    

    example function

    template
    void test(std::vector& values)
    {
        for(T value : values)
            std::cout<

    example use

    test(VECTOR(1.2f,2,3,4,5,6));
    

    though be careful about the decltype, make sure the first value is clearly what you want.

提交回复
热议问题