Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

c++ - std::vector of std::vectors contiguity

I know that std::vector<T> internally stores it's data contiguously (unless it is std::vector<bool>) both in the old C++03 standard and the new C++11.

Nice stackoverflow questions that deal with this and quote the standard: answer, answer.

What about the data inside nested vectors std::vector <std::vector <T> >? How is that stored?

If every internal vector needs to store it's data contiguously, how can it be true that &v[n] == &v[0] + n for all 0 <= n < v.size().

To phrase this slightly different, is it possible to access all the elements stored in such nested structure "simply" and sequentially (via a pointer or similar) the same way it can be done for a 1-D vector?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No. The elements of a vector are stored in a dynamically allocated block of memory; otherwise, the capacity of the vector could not increase. The vector object just holds a pointer to that block.

The requirement that the elements be stored sequentially applies only to the elements themselves, and not to any dynamically allocated members of those elements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...