Search code examples
c++stlvector

Is it more efficient to set the size of a vector up front?


If you are able to, is it more efficient to set the size of a vector up front? I intend to push_back values.


Solution

  • If you are using .push_back() to store values, it is incorrect to "set the size of the vector up front" using the .resize() member function. Rather, you would set the capacity of the vector up front using the .reserve() member function.

    Here are three correct approaches:

    // 1) Do nothing initially, use .push_back
    std::vector<int> v;
    v.push_back(1); v.push_back(2);
    
    // 2) Set the capacity initially, use .push_back
    std::vector<int> v;
    v.reserve(2);
    v.push_back(1); v.push_back(2);
    
    // 3) Set the size initiallly, use subscripts
    std::vector<int> v(2); // Set the size in construction
    v.resize(2);             // OR set the size by a call to .resize()
    v[0] = 1; v[1] = 2; 
    

    Yes, the 2nd approach is usually more size- and time-efficient than the first.

    The 2nd approach is sometimes more time-efficient than the 3rd. Or not. You should measure it to see if it even matters.