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

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

    // Before C++11
    // I used following methods:
    
    // 1.
    int A[] = {10, 20, 30};                              // original array A
    
    unsigned sizeOfA = sizeof(A)/sizeof(A[0]);           // calculate the number of elements
    
                                                         // declare vector vArrayA,
    std::vector vArrayA(sizeOfA);                   // make room for all
                                                         // array A integers
                                                         // and initialize them to 0 
    
    for(unsigned i=0; i vArrayB;                            // declare vector vArrayB
    for (unsigned i=0; i vArrayC;                            // create an empty vector vArrayC
    vArrayC.resize(sizeof(C)/sizeof(C[0]));              // enlarging the number of 
                                                         // contained elements
    for (unsigned i=0; i

提交回复
热议问题