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 ?
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 ?
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[]
.
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()