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

后端 未结 29 3117
终归单人心
终归单人心 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:47

    If your compiler supports Variadic macros (which is true for most modern compilers), then you can use the following macro to turn vector initialization into a one-liner:

    #define INIT_VECTOR(type, name, ...) \
    static const type name##_a[] = __VA_ARGS__; \
    vector name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))
    

    With this macro, you can define an initialized vector with code like this:

    INIT_VECTOR(int, my_vector, {1, 2, 3, 4});
    

    This would create a new vector of ints named my_vector with the elements 1, 2, 3, 4.

提交回复
热议问题