user1418336
user1418336

Reputation: 99

Elements of vector still reference-able after calling clear( )?

In the following code, I print the first element of a vector and its size, before and after calling clear( ) method of the in-built vector.

However, even after calling clear( ), I can still refer to the element of the vector( although the size is reset to '0').

Is this expected behaviour or have I not understood the behaviour of clear( ) well?

CODE:

#include <vector>
#include <iostream>

using namespace std;

int main(int argc, char *argv[]){
  vector<int> vec = {1, 2, 3, 4, 5};

  cout << vec[0] << " " << vec.size() << endl;

  vec.clear();

  for(auto i : vec)
    cout << i << " ";
  cout << endl;

  cout << vec[0] << " " << vec.size() << endl;
  return 0;
}

OUTPUT:

1 5

1 0

Upvotes: 0

Views: 75

Answers (1)

srdjan.veljkovic
srdjan.veljkovic

Reputation: 2548

The indexing operator of std::vector<> does not check the index. Since it's Undefined Behavior, you might get "what was there before", or it might crash (or "whatever").

You have the at member function, which will throw if index is out of range. That is:

cout << vec.at(0) << " " << vec.size() << endl;

near the end of your main() will throw.

Upvotes: 3

Related Questions