What is the overhead cost of an empty vector?

你说的曾经没有我的故事 提交于 2019-11-27 23:27:11
Éric Malenfant

As for the question as asked: It depends on the implementation. With MSVC 7.1 this:

std:: cout << sizeof(std::vector<int>) << std::endl;

gives me 16 (bytes). (3 pointers: begin, end, and end of capacity, plus an allocator)

However it should be noted that the pointer-to-vector gives it a larger overhead:

  • in both time and space in the non-empty case
  • in complexity in all cases.
Andrew Grant

It's completely implementation-dependent and you should neither assume nor rely on the details. For what it's worth it's 20-bytes using VC.

std::vector v; takes up sizeof(v) space. It might vary by implementation, so run it and find out how much it takes for you.

VS2005:

std::vector<int> *ptrToVec = new std::vector<int>();
std::vector<int> vecOfInt;

sizeof(ptrToVec) = 4
sizeof(vecOfInt) = 20

Thanks!

In Visual Studio Community 2017 (Version 15.2), running this code:

#include <iostream>
#include <vector>

using namespace std;

void main()
{
    vector<float> test;
    vector<float>* test2 = &test;
    cout << sizeof(test) << "\n";
    cout << sizeof(test2) << "\n";

    cout << "\n";
    system("pause");
}

Running in 32 bit (x86), I get 16 bytes for the vector and 4 bytes for the vector pointer.

Running in 64 bit (x64), I get 32 bytes for the vector and 8 bytes for the vector pointer.

Implementation dependant, probably a pointer and two integers for current size and capacity.

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