简体   繁体   English

元素在std :: vector和std :: deque中的连续存储位置

[英]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 ? 对于std::vectorstd::deque ,“元素的连续存储位置”是什么意思? According to cplusplus.com , std::vector s are guaranteed (and std::deque s are not) to store elements in contiguous storage locations. 根据cplusplus.com ,可以保证std::vector (不保证std::deque )将元素存储在连续的存储位置中。 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/ ). 您可以使用vector :: 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. 在Build 2014上的一次演讲 (如果您看不到整个内容,则跳到35分钟左右)显示,由于这种内存布局,vector与其他数据结构相比,性能得到了惊人的提升。

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. 由于C ++是标准化的(包括库和语言),因此可以确保vector始终将连续内存用于其元素,并且可以依靠将获得的速度提升。 That's why vector should always be your first choice for a container. 这就是为什么vector始终应该是您选择容器的首选。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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