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

后端 未结 29 3242
终归单人心
终归单人心 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条回答
  •  猫巷女王i
    2020-11-22 05:24

    Below methods can be used to initialize the vector in c++.

    1. int arr[] = {1, 3, 5, 6}; vector v(arr, arr + sizeof(arr)/sizeof(arr[0]));

    2. vectorv; v.push_back(1); v.push_back(2); v.push_back(3); and so on

    3. vectorv = {1, 3, 5, 7};

    The third one is allowed only in C++11 onwards.

提交回复
热议问题