Search code examples
c++vectorpush-back

clang tidy complains about push_back into vector in a loop


Here's my code(works fine), and the complaint of IDE: enter image description here I tried setting vector size with vector<string> result(tmp.size()); but after that, result will contain tmp.size() amount of empty strings in the front, and I don't wan't to use insert.

Is there any better workaround on this?


Solution

  • "pre-allocate" here does not mean to resize the vector to the final size, which is what vector<string> result(tmp.size()); does, but to reserve memory for the final size:

    vector<string> result;
    result.reserve(tmp.size());
    

    As mentioned in the comments that is purely meant as performance optimization. It doesn't change the behavior of the code. The reserve call will cause allocation of a memory block large enough to hold the final vector size, but doesn't construct any of the elements yet, which would still be done with push_back.

    This is a performance optimization because otherwise the final size is not known to the vector and so it may need to reallocate memory blocks multiple times during the loop, which will (asymptotically for large sizes) increase the time that the loop takes by a constant factor, assuming the length of the strings is bounded and the call to mph->getValue() is O(1), otherwise the effect will be less significant.