peoro
peoro

Reputation: 26060

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:


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

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


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?

Upvotes: 10

Views: 1290

Answers (6)

Armando
Armando

Reputation: 708

Working in multithreading environment and dynamic memory allocation might cause problem because vector is usually a continuous chunk of memory and of pointers might not!

Upvotes: 0

bcsanches
bcsanches

Reputation: 2372

If you really want a std::array you can use boost::array. It is like a common array, but support iterators and you can easily use it with STL algorithms.

Upvotes: 0

stefaanv
stefaanv

Reputation: 14392

It is even safer than having an array on the stack: how big really is your stack? how big could your array become (fixed size, but the size could be increased in later versions)?

Upvotes: 0

villintehaspam
villintehaspam

Reputation: 8744

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.

Upvotes: 5

dikamilo
dikamilo

Reputation: 667

Yep, You can use it as Array in OpenGL :) Example:

glBufferData( GL_ARRAY_BUFFER_ARB, dataVec.size() * sizeof( dataVec[0] ), &dataVec[0], GL_STATIC_DRAW_ARB );

Where dataVec is std::Vector

Upvotes: 0

jcoder
jcoder

Reputation: 30035

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.

Upvotes: 2

Related Questions