-8

I wonder about this code

vector<pair<int,int>> map;

std::cout << "hello"<< std::endl;

map.push_back(make_pair(1,2));
map.push_back(make_pair(3,4));
map.push_back(make_pair(5,6));

map.resize(0);

std::cout << map[0].first
            << map[0].second << std::endl;
std::cout << map[2].first << std::endl;

std::cout << map.size() << std::endl;
std::cout << map.capacity() << std::endl;

I resize the map to size 0, but the result shows like this:

hello
12
5
0
4

Why do I get this?

Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696
charsLEE
  • 1
  • 1
  • 2
    http://en.cppreference.com/w/cpp/container/vector/size – chris Feb 20 '18 at 07:03
  • 5
    The [`[]` operator](http://en.cppreference.com/w/cpp/container/vector/operator_at) have no bounds checking. After setting the size to zero all indexes are out of bounds and you will have [*undefined behavior*](http://en.cppreference.com/w/cpp/language/ub). – Some programmer dude Feb 20 '18 at 07:05
  • 1
    Possible duplicate of [Vector going out of bounds without giving error](https://stackoverflow.com/questions/16620222/vector-going-out-of-bounds-without-giving-error) – Tadeusz Kopec for Ukraine Feb 20 '18 at 08:03
  • you set the size to 0, the you print the size, it is 0... I would understand if you are surprised by the rest of the code, but whats wrong with the size? – 463035818_is_not_a_number Feb 20 '18 at 08:09
  • btw calling a `std::vector` as `map` is rather confusing, as there is also `std::map` – 463035818_is_not_a_number Feb 20 '18 at 08:10
  • Possible duplicate of [size vs capacity of a vector?](https://stackoverflow.com/questions/6296945/size-vs-capacity-of-a-vector) – eesiraed Feb 21 '18 at 01:22

2 Answers2

0

Size of the vector (objects it contains) is not necessarily equal to its capacity (storage space allocated for it)

Looking at http://www.cplusplus.com/reference/vector/vector/size/, you can notice this statement: "This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity."

If you check you can see the following: http://www.cplusplus.com/reference/vector/vector/capacity/ "This capacity is not necessarily equal to the vector size. It can be equal or greater, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion."

I hope this answers your question

himura
  • 1,516
  • 3
  • 19
  • 29
0

Besides the thing about the vector capacity in the other answer, accessing out of bounds indexes on vectors with the bracket operator (instead of at(), which provides bound checking) produces undefined behavior.

In other words, the behavior is not defined in the standard and can change based on things like your compiler. In your case, it apparently did not crash and outputted the values even after they're no longer in the vector.

Needless to say, you want to make sure your program is free of undefined behavior.

eesiraed
  • 4,572
  • 4
  • 15
  • 33