c++ - Writing to index of vector<int> beyond end of container -


why following work? thought writing an index of vector object beyond end of vector object cause segmentation fault.

#include <iostream> #include <vector> using namespace std; int main() {   vector<int> x(1);   x[10] = 1;   cout << x[10] << endl; } 

what implications of this? there safer way initialize vector of n elements , write those? should use push_back()?

somebody implementing std::vector might decide give minimum size of 10 or 20 elements or so, on theory memory manager has large enough minimum allocation size use (about) same amount of memory anyway.

as far avoiding reading/writing past end, 1 possibility avoid using indexing whenever possible, , using .at() indexing when can't avoid it.

i find can avoid doing indexing @ using range-based for loops and/or standard algorithms tasks. trivial example, consider this:

int main() {     vector<int> x(1);     x.push_back(1);      (auto : x)         cout << << "\n"; } 

.at() work, find useful or necessary--i suspect use less once year on average.


Popular posts from this blog