How rigorous is the bounds checking on vectors compared to heap arrays? How exactly is it checking bounds and how does that compare with how a heap array is checked?
Reserve space can be given for vector, whereas for arrays you cannot give reserved space. A vector is a class whereas an array is a datatype. Vectors can store any type of objects, whereas an array can store only homogeneous values.
A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.
Vectors are efficient and flexible. They do require a little more memory than arrays, but this tradeoff is almost always worth the benefits.
The time difference is 0.333 seconds. Or a difference of 0.000000000333 per array access. Assuming a 2.33 GHz Processor like mine that's 0.7 instruction pipeline stages per array accesses. So the vector looks like it is using one extra instruction per accesses.
A vector
will do bounds checking if you use the at()
function, for example:
std::vector<int> v(5);
v.at(3) = 10;
v.at(5) = 20; // throws an exception, std::out_of_range
However, if you use operator[]
, there is no bounds checking. (And accessing non-existent elements leads to undefined behavior.)
It should be noted, though, that most implementations will have the possibility to include bounds-checking on all iterators, which is discussed in the answers here. By default, VS2008 and below have it on in Debug and Release, VS2010 does only in Debug. gcc requires you define _GLIBCXX_DEBUG
to get checked iterators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With