Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are vectors more rigorous at checking out of bounds than heap arrays?

Tags:

c++

arrays

vector

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?

like image 621
Faken Avatar asked Jun 16 '10 19:06

Faken


People also ask

What is advantage of using vectors instead of arrays?

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.

Are vectors more efficient than arrays?

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.

Do vectors use more memory than arrays?

Vectors are efficient and flexible. They do require a little more memory than arrays, but this tradeoff is almost always worth the benefits.

How much slower are vectors than arrays?

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.


1 Answers

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.

like image 184
GManNickG Avatar answered Sep 23 '22 05:09

GManNickG