Are C++ Vectors always contiguous? [duplicate]

半世苍凉 提交于 2019-12-03 22:49:54

问题


Possible Duplicate:
Are std::vector elements guaranteed to be contiguous?

I have come across a technique in which people use a vector in C++ to receive or send data for MPI operations as it is said to store elements contiguously in memory.

However, I remain skeptical of whether this approach would remain robust for a vector of any size, especially when the vector grows to a certain size, where this assumption could break down.

Below is an example of what I am talking about :

MPI_Recv( &partials[0] , partials.size() , mpi_partial , 0, 
         DALG_ELIMINATE_REQ_MSG ,MPI_COMM_WORLD , &status );

回答1:


Yes, C++ vectors are always contiguous, regardless of size.

But that doesn't mean that they don't move around in memory as you shrink or expand them...




回答2:


The C++ working draft ( www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3126.pdf ) says at 23.4.1:

The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().




回答3:


Basically, yes. All implementations I know of are, and the standard requires vector's to have O[1] lookup which basically requires a contiguous block of memory.

Standard "you shouldn't rely on implementation details" disclaimer.



来源:https://stackoverflow.com/questions/7609169/are-c-vectors-always-contiguous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!