Vector clear vs. resize

前端 未结 4 1912
谎友^
谎友^ 2020-12-15 07:59

I read on the Internet that if you are clearing a std::vector repetitively (in a tight loop), it might be better to use resize(0) instead of

相关标签:
4条回答
  • 2020-12-15 08:11

    This sound implementation specific, and is a job for you, your library and a profiler. But as I see it, I cannot see why resize(0) should be quicker when both will in effect have to call erase(begin(),end()).

    0 讨论(0)
  • 2020-12-15 08:12

    There appears to be a difference between clear and resize(0) when the vector contains objects of a class that does not have a default constructor. For example, the following code will compile:

    #include <vector>
    
    class A {
    private:
        int x,y;
    public:
        A(int x,int y) :x(x), y(y) {}
    };
    
    int main() {
      std::vector <A> aa;
    
      aa.clear();
    }
    

    But if you substitute the aa.clear() by aa.resize(0), you get compilation error:

    error: no matching function for call to 'A::A()'
    
    0 讨论(0)
  • 2020-12-15 08:16

    I assume you mean resize(0) instead of setsize, and calling that instead of clear(), and that you're talking about std::vector. IIRC a recent answer discussed this (can't find the link), and on modern STL implementations, clear() is likely identical to resize(0).

    Previously clearing a vector might have freed all its memory (ie. its capacity also falls to zero), causing reallocations when you start adding elements again, in contrast to resize(0) keeping the capacity so there are fewer reallocations. However, I think in modern STL libraries there is no difference. If you're using an old STL implementation, or you're just paranoid, resize(0) might be faster.

    0 讨论(0)
  • 2020-12-15 08:23

    Looking at Dinkumware STL source, both effectively call erase(begin(), end());

    clear() is slightly more efficient, unsurprisingly., as it has just the one case to deal with. but I wouldn't expect it's measurable.

    0 讨论(0)
提交回复
热议问题