17

Sorry for this maybe simple and stupid question but I couldn't find it anywhere.

I just don't know how to get the size in bytes of a std::vector.

std::vector<int>MyVector;   
/* This will print 24 on my system*/   
std::cout << "Size of  my vector:\t" << sizeof(MyVector) << std::endl;

for(int i = 0; i < 1000; i++)
   MyVector.push_back(i);

/* This will still print 24...*/    
std::cout << "Size of  my vector:\t" << sizeof(MyVector) << std::endl;

So how do I get the size of a vector?! Maybe by multiplying 24 (vector size) by the number of items?

Davlog
  • 2,162
  • 8
  • 36
  • 60

3 Answers3

24

Vector stores its elements in an internally-allocated memory array. You can do this:

sizeof(std::vector<int>) + (sizeof(int) * MyVector.size())

This will give you the size of the vector structure itself plus the size of all the ints in it, but it may not include whatever small overhead your memory allocator may impose. I'm not sure there's a platform-independent way to include that.

AdamIerymenko
  • 1,299
  • 2
  • 10
  • 19
  • 5
    Wouldn't it be better to say `sizeof(MyVector)` + (sizeof(MyVector[0]) * MyVector.size())` since that would be more robust against `MyVector` becoming, say, a `std::vector>`? – Ben Apr 11 '19 at 14:48
  • what is sizeof(std::vector) mean? – xiadeye Mar 11 '21 at 07:29
20

You probably don't want to know the size of the vector in bytes, because the vector is a non-trivial object that is separate from the content, which is housed in dynamic memory.

std::vector<int> v { 1, 2, 3 };  // v on the stack, v.data() in the heap

What you probably want to know is the size of the data, the number of bytes required to store the current contents of the vector. To do this, you could use

template<typename T>
size_t vectorsizeof(const typename std::vector<T>& vec)
{
    return sizeof(T) * vec.size();
}

or you could just do

size_t bytes = sizeof(vec[0]) * vec.size();
kfsone
  • 23,617
  • 2
  • 42
  • 74
  • 3
    `sizeof` is evaluated at compile time. vec[0] evaluates to the return type of vec.operator [] – kfsone Nov 23 '17 at 02:54
4

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.

To get the size of the container implementation you can do what you currently are:

sizeof(std::vector<int>);

To get the size of all the elements stored within it, you can do:

MyVector.size() * sizeof(int)

Then just add them together to get the total size.

Thomas Russell
  • 5,870
  • 4
  • 33
  • 68
  • 7
    "I wanna know how much space it takes of my memory" -> vector has "capacity()" elements – joy Jun 22 '13 at 20:00
  • As mentioned above, I think `sizeof(MyVector[0])` is better than `sizeof(int)` because that'll stay correct if you change the type of `MyVector`. – Ben Apr 11 '19 at 14:49