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

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

    In C++11:

    #include 
    using std::vector;
    ...
    vector vec1 { 10, 20, 30 };
    // or
    vector vec2 = { 10, 20, 30 };
    

    Using boost list_of:

    #include 
    #include 
    using std::vector;
    ...
    vector vec = boost::assign::list_of(10)(20)(30);
    

    Using boost assign:

    #include 
    #include 
    using std::vector;
    ...
    vector vec;
    vec += 10, 20, 30;
    

    Conventional STL:

    #include 
    using std::vector;
    ...
    static const int arr[] = {10,20,30};
    vector vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
    

    Conventional STL with generic macros:

    #include 
    #define ARRAY_SIZE(ar) (sizeof(ar) / sizeof(ar[0])
    #define ARRAY_END(ar) (ar + ARRAY_SIZE(ar))
    using std::vector;
    ...
    static const int arr[] = {10,20,30};
    vector vec (arr, ARRAY_END(arr));
    

    Conventional STL with a vector initializer macro:

    #include 
    #define INIT_FROM_ARRAY(ar) (ar, ar + sizeof(ar) / sizeof(ar[0])
    using std::vector;
    ...
    static const int arr[] = {10,20,30};
    vector vec INIT_FROM_ARRAY(arr);
    

提交回复
热议问题