I was just messing around and learning about vectors as well as structs, and at one point, I tried outputting the size of a vector in bytes. Here's the code:
#include <iostream>
#include <vector>
struct Foo{
std::vector<int> a;
};
int main()
{
using std::cout; using std::endl;
Foo* f1 = new Foo;
f1->a.push_back(5);
cout << sizeof(f1->a) << endl;
cout << sizeof(f1->a[0]) << endl;
delete[] f1;
}
The output is 24
and 4
.
Obviously the second line printed 4, because that is the size of an int. But why exactly is the other value 24? Does a vector take up 24 bytes of memory? Thanks!
class std::vector<int>
. It's implementation-dependant, and it's the sum of the sizes of the members of such a class. Usually a pointer to the underlying C-style array and various members like size, capacity and so on. – Contrivedelete[] f1
is incorrect, it should bedelete f1
only – Nerlandnew/delete
. We'd writeFoo f1;
andfi.push_back
(dot not arrow). – Dasha