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

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

    In C++0x you will be able to do it in the same way that you did with an array, but not in the current standard.

    With only language support you can use:

    int tmp[] = { 10, 20, 30 };
    std::vector v( tmp, tmp+3 ); // use some utility to avoid hardcoding the size here
    

    If you can add other libraries you could try boost::assignment:

    vector v = list_of(10)(20)(30);
    

    To avoid hardcoding the size of an array:

    // option 1, typesafe, not a compile time constant
    template 
    inline std::size_t size_of_array( T (&)[N] ) {
       return N;
    }
    // option 2, not typesafe, compile time constant
    #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
    
    // option 3, typesafe, compile time constant
    template 
    char (&sizeof_array( T(&)[N] ))[N];    // declared, undefined
    #define ARRAY_SIZE(x) sizeof(sizeof_array(x))
    

提交回复
热议问题