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

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

    "How do I create an STL vector and initialize it like the above? What is the best way to do so with the minimum typing effort?"

    The easiest way to initialize a vector as you've initialized your built-in array is using an initializer list which was introduced in C++11.

    // Initializing a vector that holds 2 elements of type int.
    Initializing:
    std::vector ivec = {10, 20};
    
    
    // The push_back function is more of a form of assignment with the exception of course
    //that it doesn't obliterate the value of the object it's being called on.
    Assigning
    ivec.push_back(30);
    

    ivec is 3 elements in size after Assigning (labeled statement) is executed.

提交回复
热议问题