tags:

views:

101

answers:

4

How can I predict the size of a vector?

#include <vector>
#include <iostream>
using namespace std;

int main() {
    cout << sizeof(vector<char[8]>) << endl;
    cout << sizeof(vector<char[16]>) << endl;
    return 0;
}

[starlon@localhost LCDControl]$ ./test 
12
12
+1  A: 

There is a method called size()
This tells you how many elements are contained inside.
But the size of the object will not reflect this as it just contains a pointer to the actuall data.

By the way you are declaring vectors of arrays of char. Is this what you really want?

Also this:

std::cout << std::vector<X>(Y) << "\n";

Should (proobably) always return the same value not matter what X or Y is.

Martin York
+9  A: 

Since vector<> itself is a class that does its own dynamic memory management, using the sizeof operator to ask it about size is not terribly meaningful. I suspect you will find that the value you calculate above will always be 12.

You can ask a vector how many elements it contains using the .size() method. Also, the .capacity() method will tell you how many elements it has actually allocated memory for (even if they're not all in use yet).

Remember that sizeof is evaluated at compile time, so it cannot know how many elements are inserted into the container later, at run time.

Greg Hewgill
A: 

What do you want to do exactly, do you want to know how much memory a std::vector that contains 8 or 16 chars takes up?

If that's what you want, your code above is wrong. What your code above shows is the size of a std::vector, in which the elements are an array of chars. It gives you the size of the std::vector object itself - but doesn't say anything about the amount of memory that the elements take up. That memory is allocated dynamically by the vector.

It's not possible to know this with the sizeof operator, because sizeof is a compile-time operator, while the memory for the elements is dynamically allocated at runtime.

Jesper
Well, yes I know it's wrong. That's about as close to the actual "right way" I can come up with. I was hoping for the "right way", hence the question.
Scott
The right way to do what? What you are trying to do does not make sense. Maybe tell us what you are trying to do that makes you think you need to know the size.
Martin York
Well, I have a vector, and I wanted to memset it to 0. Maybe I should just use char[8][8] instead and realloc as needed?
Scott
@Scott: you do not need to `memset` vectors. Just initialize it with the needed size, the memsetting will be done automatically. Refer to the documentation (e.g. at <cppreference.com>).
Konrad Rudolph
+2  A: 

sizeof always returns the size of the first level object/type. It does not attempt to measure the amount of memory that object points to in other locations. The 12 bytes that sizeof returns reflects the sizeof the data members of vector. One of those members is a pointer which points to the actual data.

Brad