-2

I found that, vector.clear() does retain value.

Vector.clear() retain values which can be accessed through vector[index]. But if I do, for(auto &i:vector) { cout <<a;} then, it doesn't disclose any values. What is the reason of that ?

  • 1
    If you use an index that is equal to or larger than the size of the vector, you're indexing out of bounds and that leads to *undefined behavior*. Just don't do it! – Some programmer dude Jan 10 '23 at 07:00
  • In C++ the fact that a program compiles and runs and even seems to give the "correct" output doesn't mean the program is correct. As said you access memory you no longer own (and other code is allowed to overwrite it, that this hasn't happened yet is pure bad luck. Bad luck because it doesn't show you have done something wrong) – Pepijn Kramer Jan 10 '23 at 07:05
  • *"Undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has UB. The program may just crash."* – Jason Jan 10 '23 at 07:05

2 Answers2

0

Accessing a vector out of bounds leads to undefined behavior. It may "work." Or maybe not. There is no guarantee.

From the operator[] documentation at cppreference.com:

Notes

Unlike std::map::operator[], this operator never inserts a new element into the container. Accessing a nonexistent element through this operator is undefined behavior.

If you want bounds checking on a std::vector use at rather than operator[].

Chris
  • 26,361
  • 5
  • 21
  • 42
0

The elements have been marked as cleared, this does not necessarily mean they are gone. When you access via vec[1] you are entering the fields of undefined behaviour.

If you were to try vector.at(1), your program would correctly raise an std::out_of_range exception.


The reason your for (auto &i : vec) loop is empty, is that it calls .begin() and .end() on your vector, and that range is empty since these iterators are equal after a .clear()

Stack Danny
  • 7,754
  • 2
  • 26
  • 55