获取向量的字节大小 [英] Getting the size in bytes of a vector

查看:102
本文介绍了获取向量的字节大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,这个简单而愚蠢的问题,但我找不到它。

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

我只是不知道如何获取a的大小(以字节为单位)

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;

那么我如何获得向量的大小?也许通过将24(向量大小)乘以项目数?

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

推荐答案

Vector将其元素存储在内部分配的内存数组中。您可以这样做:

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

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

这将为您提供向量结构本身的大小以及其中所有int的大小它,但是它可能不包括您的内存分配器可能施加的任何少量开销。我不确定是否存在一种独立于平台的方式。

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.

这篇关于获取向量的字节大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆