vector help

Started by
3 comments, last by Zahlman 15 years, 10 months ago
when we write a statement in our c++ program vector v <int> ; (or like that i dont remember exactly the syntax of vector) how much space does it occupy in memeory ........
Advertisement
sizeof(v);

That should be the size of the vector excluding any elements you added through calls like push_back(). The question begs to be asked: Why do you care?
that means if we don't push any values in it, then no space in the memory will be used ?
Quote:Original post by y2jsave
that means if we don't push any values in it, then no space in the memory will be used ?


No. Just declaring a vector occupies space. However sizeof() will not reflect amount of space occupied by elements you add to the vector.
Quote:Original post by y2jsave
when we write a statement in our c++ program
vector v <int> ; (or like that i dont remember exactly the syntax of vector)
how much space does it occupy in memeory ........


There will be, for normal implementations*, two chunks of memory allocated: the object itself, and the storage for the elements. The element storage will always be dynamically allocated, even if the object itself is on the stack.

The object itself is typically** a structure consisting of a pointer and two integers, or of three pointers. One pointer points to the beginning of the element storage. If the other members are integers, they count the size (number of elements actually stored) and capacity (number of elements that fit in the current storage). If they're pointers, they point to corresponding positions: the insertion point where a push_back()ed element would go, and just past the end of the storage.

Thus, the object itself generally*** takes up 12 bytes of memory, each pointer or integer being 4 bytes. The element storage is* an array, so it will take up size equal to the element size times capacity. However, you don't control the capacity directly (you only set a minimum - either explicitly, or implicitly by adding more elements than can fit in the old storage). You can ask the vector for its current .capacity(), however, and thus find out the total memory allocation.

* The language standard doesn't say exactly how things are implemented, but it's next to impossible to do it any other way and still meet the requirements the standard *does* impose.
** I.e., this is the natural way to do things. The compiler could easily do it another way, but it would probably provide no advantage.
*** This is what happens with the "typical" assumptions from above, if we choose reasonable data types and are targeting normal home computer software. But when we write portable C++ code, we try not to make these assumptions - since they generally don't, or shouldn't, matter anyway.

This topic is closed to new replies.

Advertisement