-1

I have vector<Mat> images vector. I like to delete the vector and its contents. I know a few approaches. I like to know which one is more effective. They are

(1)images.erase();
(2)images.clear();
   vector<Mat>().swap(images);
(3)for(unsigned int l = 0; l < images.size(); l++){
        images[l].release();
   }

Thanks

Spaceghost
  • 6,835
  • 3
  • 28
  • 42
batuman
  • 7,066
  • 26
  • 107
  • 229

2 Answers2

1

You ask for most “effective”. There is a possibility that you meant “efficient”. Most “effective” is the method that in most case do what you want, clearing that vector.

And that is the clear() method, because erase() adds requirements on the items, i.e. it's less universally applicable.

[1]cppreference.com about erase:

T must meet the requirements of MoveAssignable.

Probably Mat is move-assignable or copyable, but if it isn't, then you just can't use erase.


Method 3, looping over all vector items and using an item-specific way to return each item to a destructible nullstate/emptystate, is clearly the least effective as it only applies to item types with nullstates/emptystates. Note, since it's not included in the example, that you need to adjust the vector size after that.


If instead of effective you really meant efficient, then it all depends on the type Mat, your compiler's implementation of std::vector, the compiler options, the environment your program is running in, etc. I.e. then you have no recourse but to measure. A nice consequence of measuring can be that you find that no particular optimization is needed, so then you can most probably just use clear as the most clear way, which is what's generally most important. ;-)


[1] At (http://en.cppreference.com/w/cpp/container/vector/erase).

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
0

Clear will be the fastest one because it's gonna keep the allocated memory so, if you plan on reusing that vector, that's the best one to pick.

While the swap trick will force the vector to free the memory, which should be technically slower.

Of course, you can only use swap or clear if your Mat class has a well written destructor, otherwise you need to loop and release them , and then clear the vector.

Jts
  • 3,447
  • 1
  • 11
  • 14