sizeof() a vector
I have a vector<set<char> >
data structure (transactions database) and I want to know the size of it. When I use sizeof() with each set<char>
the size is 24 in spite of the set contains 3, 4 or 5 chars. Later, when I use sizeof() with the vector<set<char> >
the size is 12... I suppose this is not the way to know the size of a data structure. Any help?
Thanks.
You want vector::size()
and set::size()
.
Assuming v
is your vector, do this:
size_t size = 0;
for (vector<set<char> >::const_iterator cit = v.begin(); cit != v.end(); ++cit) {
size += cit->size();
}
sizeof()
is giving you the in-memory size of the object/type it is applied to, in multiples of sizeof(char)
(usually one byte). If you want to know the in-memory size of the container and its elements, you could do this:
sizeof(v) + sizeof(T) * v.capacity(); // where T is the element type
sizeof
returns size of object itself. if it contains pointer to array for example it will not count size of array, it will count only size of pointer (4 on 32 bits) for vector use .size
Vector is implemented using internal pointers to the actual storage. Hence sizeof() will always return the same result which does not include the data storage itself. Try using the vector::size()
method instead. This will return the number of elements in the vector.