c++ - exceeding vector does not cause seg fault -


i puzzled @ result of bit of code:

std::vector<int> v; std::cout << (v.end() - v.begin()) << std::endl; v.reserve(1); std::cout << (v.end() - v.begin()) << std::endl; v[9] = 0; std::cout << (v.end() - v.begin()) << std::endl; 

the output:

0 0 0 

so... first of all... end() not point end of internal array last occupied cell... ok, why result of iterator subtraction still 0 after reserve(1). but, why still 0 after 1 cell has been filled. expected 1 result, because end() should return iterator second internal array cell. furthermore, why on earth not getting seg fault accessing tenth cell v[9] = 0, while vector 1 cell long?

v[9] = 0;, you're accessing vector out of bound, it's ub. may crash in cases, , may not. nothing guaranteed.

and v[9] = 0;, don't add element @ all. need use push_back or resize:

v.push_back(0); // has 1 element v.resize(10);   // has 10 elements 

edit

why v[index] not create element?

because std::vector::operator[] doesn't that.

returns reference element @ specified location pos. no bounds checking performed. unlike std::map::operator[], operator never inserts new element container.

so it's supposed vector has sufficient elements subscript operator.

btw: suppose vector should when write v[9] = 0? before set 10th element 0, has push 10 elements first. , how set values? 0? so, won't it, issue depends on yourself.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -