Size of std::array, std::vector and raw array

Jan 8, 2012 at 1:43pm
How can I know the size of std::array, std::vector and raw array if they have same number of members and types. With size I mean the memory they occupy as a whole or in other words, I don't want any bad_alloc.

Thanks in advance.
Last edited on Jan 8, 2012 at 1:43pm
Jan 8, 2012 at 2:06pm
If it is a POD type that is stored in the array/vector you can just use sizeof on raw arrays and std::array. With std::vector<T> v; it's a bit more complicated. First we have the size of the vector itself sizeof(v). The size occupied by the elements v.capacity() * sizeof(T) so in total sizeof(v) + v.capacity() * sizeof(T). Dynamic allocations might have additional overhead but that is ignored here.
Jan 8, 2012 at 10:34pm
I think that capacity() itself returns the size of the allocated memory for its elements. So no need to multiply it with sizeof(T).

For example see:
http://www.cplusplus.com/reference/stl/vector/capacity/
Jan 8, 2012 at 10:40pm
No. capacity() returns the number elements that the vector has allocated space for, so the multiplication is needed.
Topic archived. No new replies allowed.