0

I have a vector of events, with the first one being a guard for easier computations. I have implemented a reset operation as follows:

void reset()
{
    myVector.resize(1);
}

so that only the first one element remains. Does this operation reallocate memory? I will call it in a loop, so I would like it to be very time-efficient. If it does, then what would be an efficient alternative?

Grzenio
  • 35,875
  • 47
  • 158
  • 240

3 Answers3

1

The only functions which allocate memory are reserve and the insertions (insert and push_back). And shrink_to_fit in C++11.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • 1
    but `shrink_to_fit()` is a non-binding request – TemplateRex Feb 06 '13 at 11:42
  • So resize() will only reallocate memory if the requested size is smaller than the size of the underlying container? And the underlying container is never sized down? – Grzenio Feb 06 '13 at 11:44
  • @Grzenio: `resize` may reallocate memory if the requested size is larger that the current capacity. It is guaranteed not to reallocate if the requested size is smaller than the current capacity. It's defined as being equivalent to `erase` when it reduces the size, and equivalent to appending elements when it increases the size. – Steve Jessop Feb 06 '13 at 11:56
  • @rhalbersma But it may reallocate. – James Kanze Feb 06 '13 at 11:57
  • @JamesKanze: maybe wasn't clear to a reader that by "functions which allocate" you mean "functions which are permitted to allocate" as opposed to, say, "functions guaranteed to allocate every time they're called". None of them is *guaranteed* to allocate (which is why in context that wasn't what you meant), but `shrink_to_fit` is the one that most blatantly isn't required to do anything, ever. – Steve Jessop Feb 06 '13 at 11:58
1

Does this operation reallocate memory?

If there are no elements in the vector, then the first call to resize(1); will do the allocation. Otherwise, no.

what would be an efficient alternative?

The efficient alternative is to assign the vector with enough space during it's construction. Then you are sure no reallocation is going to happen.

BЈовић
  • 62,405
  • 41
  • 173
  • 273
1

If the new size is less than the current size, std::vector::resize doesn't allocate memory. It simply destroys the remaining elements in the vector. Complexity in the worst case is linear in the number of elements.

Daniel Martín
  • 7,815
  • 1
  • 29
  • 34