resize() doesnt work help

i use code blocks and resize function does nothing whenever i return the value of a[1] it doesn't give me the address nor the error but gives me the number 6

1
2
3
4
5
      vector<int> a(2);
    a[0]=5;
    a[1]=6;
    a.resize(0);
    cout<<a[1]<<endl;


output is

6
The memory is still there. You are just not supposed to use it.
resize(n)
it said in the reference whenever the value of the n is smaller that the size of the vector it deletes what's beyond that number.. can u explain what u just said according to this pls
If the size is 0 you are not allowed to access elements at index 0 or 1. If you do the behaviour is undefined. That means anything is allowed to happen, that includes crashing, showing an error message or simply returning the value that was previously stored at that location.


What happens in practice is that the vector keeps the same piece of memory in case you are going to insert elements later and the [] operator doesn't do any range checking so it simply just returns the old value. It doesn't overwrite the old values or anything because that would just be a waste of processor time.


If you instead use the at member function it would check if the index is valid and throw an exception if it's not.

 
a.at(0); // Throws a std::out_of_range exception if a is empty.  

http://www.cplusplus.com/reference/vector/vector/at/
Last edited on
thank you so much that helped (y)
Topic archived. No new replies allowed.