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

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

    There are various ways to hardcode a vector, i will share few ways:

    1. Initializing by pushing values one by one
    // Create an empty vector 
        vector vect;  
    
        vect.push_back(10); 
        vect.push_back(20); 
        vect.push_back(30); 
    
    1. Initializing like arrays
    vector vect{ 10, 20, 30 };
    
    1. Initializing from an array
        int arr[] = { 10, 20, 30 }; 
        int n = sizeof(arr) / sizeof(arr[0]); 
    
        vector vect(arr, arr + n); 
    
    1. Initializing from another vector
        vector vect1{ 10, 20, 30 }; 
    
        vector vect2(vect1.begin(), vect1.end()); 
    

提交回复
热议问题