Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: is it safe to work with std::vectors as if they were arrays?

I need to have a fixed-size array of elements and to call on them functions that require to know about how they're placed in memory, in particular:

  • functions like glVertexPointer, that needs to know where the vertices are, how distant they are one from the other and so on. In my case vertices would be members of the elements to store.

  • to get the index of an element within this array, I'd prefer to avoid having an index field within my elements, but would rather play with pointers arithmetic (ie: index of Element *x will be x - & array[0]) -- btw, this sounds dirty to me: is it good practice or should I do something else?


Is it safe to use std::vector for this?

Something makes me think that an std::array would be more appropriate but:

  • Constructor and destructor for my structure will be rarely called: I don't mind about such overhead.

  • I'm going to set the std::vector capacity to size I need (the size that would use for an std::array, thus won't take any overhead due to sporadic reallocation.

  • I don't mind a little space overhead for std::vector's internal structure.

  • I could use the ability to resize the vector (or better: to have a size chosen during setup), and I think there's no way to do this with std::array, since its size is a template parameter (that's too bad: I could do that even with an old C-like array, just dynamically allocating it on the heap).


If std::vector is fine for my purpose I'd like to know into details if it will have some runtime overhead with respect to std::array (or to a plain C array):

I know that it'll call the default constructor for any element once I increase its size (but I guess this won't cost anything if my data has got an empty default constructor?), same for destructor. Anything else?

like image 479
peoro Avatar asked Dec 24 '10 10:12

peoro


2 Answers

Vectors are guaranteed to have all elements in contigous memory, so it is safe to use in your scenario. There can be a small performance hit compared to c-style arrays, for instance due to index validations done by the vector implementation. In most cases, the performance is determined by something else though, so I wouldn't worry about that until actual measurements of performance show that this a real problem.

As pointed out by others, make sure that you don't reallocate the vector while you are making use of the data stored in it if you are using pointers to elements (or iterators) to access it.

like image 120
villintehaspam Avatar answered Sep 22 '22 13:09

villintehaspam


It's fine to treat the data in a std::vector as an array, get a pointer to the start of it with &v[0]. Obviously if you do anything that can reallocate the data then then you pointers will probably be invalidated.

like image 37
jcoder Avatar answered Sep 19 '22 13:09

jcoder