Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I discover the size/length(in bytes) of a std::vector?

Tags:

I have a vector and I want to write and read it to a file but it is not possible to determine the logical size of a vector using the sizeof operator.

So what shall I do?

like image 450
Vahid Haratian Avatar asked Jan 09 '13 15:01

Vahid Haratian


People also ask

How do you find the size of a vector in a byte?

The size of a vector is split into two main parts, the size of the container implementation itself, and the size of all of the elements stored within it. Then just add them together to get the total size.

How many bytes is a std::vector?

So there is no surprise regarding std::vector. It uses 4 bytes to store each 4 byte elements.

How do you find the size of a vector in C++?

To get the size of a C++ Vector, you can use size() function on the vector. size() function returns the number of elements in the vector.

How do you find the vector size of a vector?

To get the size of vector test[x] you do test[x]. size() . Nice to see you use C++11 elements!


1 Answers

A c++ std::vector has a method size() which returns its size.

EDIT: as I get it now you need to compute the memory a given vector uses. You can't use sizeof for that as a vector uses dynamic memory and stores only a pointer of a dynamic array containing its elements. So my best suggestion would be to multiply the memory each element requires by the number of elements. Note this again will not work if the objects stores a pointer to some dynamically allocated objects - you will have again to compute their sizes separately.

There is no easy way to compute the memory a vector size in bytes in c++ that I know of.

like image 143
Ivaylo Strandjev Avatar answered Oct 28 '22 01:10

Ivaylo Strandjev