Vector transparent and size.

I read on the Internet that if you clean std::vectorrepeatedly (in a narrow loop), it is better to use resize(0)instead clear(), as this can be faster. I am not sure about that. Does anyone have a definitive answer to this?

+5
source share
4 answers

I assume that you mean resize(0)instead setsize, and call it instead clear(), and what you are talking about std::vector. The IIRC's recent response discussed this (cannot find a link), and about modern STL implementations clear()are most likely identical resize(0).

(.. ), , resize(0) , . , , STL . STL , resize(0) .

+13

STL Dinkumware, erase(begin(), end());

clear() , , . , .

+2

This is a specific sound implementation, and this is the job for you, your library and profiler. But, as I see it, I don’t understand why resizing (0) should be faster when both actions have to call erase (begin (), end ()).

+1
source

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

#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 replace aa.clear()with aa.resize(0), you will get a compilation error:

error: no matching function for call to 'A::A()'
0
source

All Articles