1

When a vector exists and tries to erase the back of that vector. Is it efficient to use an 'vector.assign' in terms of time complexity? Or is it efficient to use 'vector.erase'?

Please let me know the time complexity in each case.

[For example]

vector<int> v = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// 1. use assign
v.assign(v.begin(), v.begin() + 5);

// 2. use erase
v.erase(v.begin() + 5, v.end());

  • 1
    They have two radically different behaviours. `assign` writes over. The assigned elements are still in the vector. `erase` removes. The erased elements are no longer in the vector. Which behavour do you want? – user4581301 Nov 15 '20 at 03:56
  • 4
    According to [cppreference](https://en.cppreference.com/w/cpp/container/vector/assign) it's undefined behavior to call `v.assign(v.begin(), ...);` in the first place because `v.begin()` is an iterator into `v`. – Nathan Pierson Nov 15 '20 at 03:58
  • Good eyes, @NathanPierson . Didn't spot the overwrite. – user4581301 Nov 15 '20 at 03:59
  • 3
    just use resize: https://en.cppreference.com/w/cpp/container/vector/resize – doug Nov 15 '20 at 04:00
  • I would like to use vectors that consist only of elements from the beginning section of vectors to a certain index. @user4581301 – user13276203 Nov 15 '20 at 04:05
  • Then vector v2; v2.assign(v.begin(), v.begin() + 5); v = v2; and v.erase(v.begin() + 5, v.end()); Which is more efficient? @NathanPierson – user13276203 Nov 15 '20 at 04:09
  • oh Is resize faster than the two above? @doug – user13276203 Nov 15 '20 at 04:13
  • 1
    Test and measure to be sure, but `resize` for a `vector` of `int` should merely be moving the end pointer. With a more complex datatype in the `vector` you would have to also factor in the calling of destructors. Note that it won't even give the excess memory back. – user4581301 Nov 15 '20 at 04:18
  • 1
    @user4581301 `erase()` doesn't give excess memory back either. For good reasons. There's a method called `shrink_to_fit()` that's implementation dependent and if it does it's likely to copy the vector and release all the memory in the first. Bleah. – doug Nov 15 '20 at 04:26
  • 1
    For more on what @doug and I are talking about, consult vector's Iterator invalidation rules. Some lovely people have aggregated the library container invalidation rules and translated them from Language Lawyer to English in the aptly-named [Iterator invalidation rules](https://stackoverflow.com/questions/6438086/iterator-invalidation-rules) question. – user4581301 Nov 15 '20 at 04:31

1 Answers1

2

I would like to use vectors that consist only of elements from the beginning section of vectors to a certain index.

It's most efficient to use resize, because that's what that function is for.

For what its worth, self-assignment is not allowed for containers.

Nicol Bolas
  • 378,677
  • 53
  • 635
  • 829