We know that std::vector gives a continuous memory layout, while std::list gives a linked memory layout, and my question is what is the memory layout of std::vector< std::list >? Does it contain contents of std::list or it just contains several pointers to the lists?
Although it is true that std::list
keeps its elements in separately allocated memory locations connected with each other as a linked list, a small area of memory is needed for the header structure of the list itself. It is this structure that gets allocated when you create an instance of std::list<T>
.
A vector of std::list<T>
consists of these "header" items for the individual linked lists, allocated in a contiguous region of memory:
It's the same as any other std::vector<T>
(unless T=bool
): it contains an array of T
. In this case, it is an array of std::list
. A std::list
object is basically a bookkeeping structure for the list of objects it "contains"; the actual elements are in separately-allocated chunks outside of this structure (and therefore outside the memory block managed by std::vector<std::list<T> >
).
Note that std::vector
doesn't care what T
is as long as it is copyable. In principle, you could design a container that had specializations for carrying other containers, but this isn't how std::vector
works.
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.