sizeof() a vector

混江龙づ霸主 提交于 2019-11-27 22:12:35

You want vector::size() and set::size().

Assuming v is your vector, do this:

size_t size = 0;
for (vector<set<char> >::const_iterator cit = v.begin(); cit != v.end(); ++cit) {
    size += cit->size();
}

sizeof() is giving you the in-memory size of the object/type it is applied to, in multiples of sizeof(char) (usually one byte). If you want to know the in-memory size of the container and its elements, you could do this:

sizeof(v) + sizeof(T) * v.capacity(); // where T is the element type

sizeof returns size of object itself. if it contains pointer to array for example it will not count size of array, it will count only size of pointer (4 on 32 bits) for vector use .size

Vector is implemented using internal pointers to the actual storage. Hence sizeof() will always return the same result which does not include the data storage itself. Try using the vector::size() method instead. This will return the number of elements in the vector.

sizeof() is computed at compile time, so there is no way it can tell you how many elements it has inside.

Use the size() method of the vector object.

vector in STL is a class template, when you give template parameter inside <SomeType> following vector, C++ compiler generated code for a class of type SomeType. So when you populate the vector using push_back, you are actually inserting another object of SomeType so when you request .size() from the compiler it gives you the number of SomeType objects inserted by you.
Hope that helps!

Use vector::size() member function to find out number of items in the vector. Hint - they are allocated on the free store.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!