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

后端 未结 29 2650
终归单人心
终归单人心 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<int> 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<int> v = list_of(10)(20)(30);
    

    To avoid hardcoding the size of an array:

    // option 1, typesafe, not a compile time constant
    template <typename T, std::size_t N>
    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 <typename T, std::size_t N>
    char (&sizeof_array( T(&)[N] ))[N];    // declared, undefined
    #define ARRAY_SIZE(x) sizeof(sizeof_array(x))
    
    0 讨论(0)
  • 2020-11-22 05:32

    The easiest way to do it is:

    vector<int> ints = {10, 20, 30};
    
    0 讨论(0)
  • 2020-11-22 05:34

    In C++11:

    static const int a[] = {10, 20, 30};
    vector<int> vec (begin(a), end(a));
    
    0 讨论(0)
  • 2020-11-22 05:34

    you can do that using boost::assign.

    vector<int> values;  
    values += 1,2,3,4,5,6,7,8,9;
    

    detail here

    0 讨论(0)
  • 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<decltype(first)> ret(arr, arr + sizeof(arr) / sizeof(*arr)); \
       return ret;})()
    

    example function

    template<typename T>
    void test(std::vector<T>& values)
    {
        for(T value : values)
            std::cout<<value<<std::endl;
    }
    

    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.

    0 讨论(0)
  • 2020-11-22 05:38

    Before C++ 11 :

    Method 1=>

    vector<int> v(arr, arr + sizeof(arr)/sizeof(arr[0]));
    vector<int>v;
    

    Method 2 =>

     v.push_back(SomeValue);
    

    C++ 11 onward below is also possible

    vector<int>v = {1, 3, 5, 7};
    
    0 讨论(0)
提交回复
热议问题