-1

I'm new to C++ and i try many things to understand how it works.

In this code i don't understand why my first value of vec.end() is ok and after the erase method my vec.end() is equal to my last element(5).

One explanation would be that vec.end() would point to ex vec[4] (5) but when I apply once again vec.erase(), vec.end () is still equal to 5.

I would be very grateful if someone could explain to me why this is happening.

#include <iostream>
#include <vector>

int main()
{
  std :: vector<int> vec{1 , 2 , 3 , 4 , 5};

  auto it = vec.begin();
  std :: cout << *(vec.end()) << std :: endl;
  std :: cout << vec.size() << std :: endl;
  vec.erase(it);
  std :: cout << *(vec.end()) << std :: endl;
  std :: cout << vec.size() << std :: endl;

  return 0;
}
  • 5
    `*(vec.end())` is never allowed. `end` is one past the end. You may be thinking of `vec.back()` if you want the last element. – François Andrieux Jul 07 '20 at 18:49
  • See [Iterator invalidation rules](https://stackoverflow.com/questions/6438086/iterator-invalidation-rules) for additional information on how `erase` (and other modifications) can change an iterator's view of a container. – user4581301 Jul 07 '20 at 18:55
  • @FrançoisAndrieux Ik that end is one past the end but i dont understand why before erase *(vec.end()) = something good like 19231541231 and after erase *(vec.end()) = last element in every case. – Stephen Gregory Jul 07 '20 at 18:57
  • 3
    @StephenGregory It's undefined behaviour, e.g. anything could happen. Really anything (at least in theory). Don't think too much about it, because there is no logic to undefined behaviour. Just avoid it. – Lukas-T Jul 07 '20 at 18:59
  • 2
    @StephenGregory It is just a coincidence due to how `std::vector` is implemented. It seems you expect Undefined Behavior to do "something you didn't expect" such as printing oddly large numbers, and that you are surprised that it just printed 5 instead. This is the wrong expectation to have, because having *any* expectation about how Undefined Behavior will behave is incorrect. Anything can happen with `*(vec.end())`, even oddly tame or apparently predictable outcomes. – François Andrieux Jul 07 '20 at 19:02

1 Answers1

0

vec.end() always point to a virtual element after the last element. When you use *vec.end() the return value is invalid and could be anything. You can see this by printing (*(vec.end()-1)) and seeing that is equal to last element.

Ali Askari
  • 515
  • 3
  • 8