简体   繁体   中英

Elements' contiguous storage locations in std::vector and std::deque

What does "elements' contiguous storage locations" mean with respect to std::vector and std::deque ? According to cplusplus.com , std::vector s are guaranteed (and std::deque s are not) to store elements in contiguous storage locations. But how can I see it in the code? Both have a random access iterator so in both situations we can add some random offset to random container's reference and all should be ok, right?

You can see is by using vector::data(), which returns a pointer to your contiguous data ( http://www.cplusplus.com/reference/vector/vector/data/ ).

You can then use pointer based access to the elements (although, it's much safer and maitenable to use the standard container operations), for example if you want to use a function which expects a pointer or you if you think it could leverage performance.

This member function exists also for arrays and strings, because they also have contiguous elements.

This member doesn't exist for containers which do not guarantee contiguity, such as deque, lists or stacks.

The reason you care is that this implementation detail makes a huge difference to performance. You don't need to prove it by trying to access elements with a pointer, because you can just count on it. A talk at Build 2014 (jump to about 35 minutes if you can't watch the whole thing) showed the amazing performance boost that vector has over other data structures as a result of this memory layout.

Since C++ is standardized, both library and language, you can be sure that vector will always use contiguous memory for its elements, and you can count on the speed boost you will get. That's why vector should always be your first choice for a container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM