Are C++ Vectors always contiguous? [duplicate]

2020-03-06 02:14发布

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 );

3条回答
迷人小祖宗
2楼-- · 2020-03-06 02:39

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楼-- · 2020-03-06 02:50

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.

查看更多
等我变得足够好
4楼-- · 2020-03-06 02:58

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...

查看更多
登录 后发表回答