免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2310 | 回复: 1
打印 上一主题 下一主题

vector.size(),vector.capacity(),sizeof(vector)的区别 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-08-07 13:41 |只看该作者 |倒序浏览
问题:vector.size(),vector.capacity(),sizeof(vector)是怎么计算的,结果跟什么有关?

环境:
gcc version 3.2.3 20030502 (Red Hat Linux 3.2.3-47)

代码:
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<list>
#include<functional>
using namespace std;

#define number 33
vector<bool> vbool(number);
vector<int> vint(number);
vector<double> vdouble(number);
vector<string> vstring(number);

int main()
{
        cout << "vbool size == " << vbool.size() << endl;
        cout << "vint size == " << vint.size() << endl;
        cout << "vdouble size == " << vdouble.size() << endl;
        cout << "vstring size == " << vstring.size() << endl;

        cout << "vbool bytes == " << sizeof(vbool) << endl;
        cout << "vint bytes == " << sizeof(vint) << endl;
        cout << "vdouble bytes == " << sizeof(vdouble) << endl;
        cout << "vstring bytes == " << sizeof(vstring) << endl;

        cout << "vbool capacity == " << vbool.capacity() << endl;
        cout << "vint capacity == " << vint.capacity() << endl;
        cout << "vdouble capacity == " << vdouble.capacity() << endl;
        cout << "vstring capacity == " << vstring.capacity() << endl;

        return 0;
}

运行结果:
vbool size == 33
vint size == 33
vdouble size == 33
vstring size == 33

vbool bytes == 20
vint bytes == 12
vdouble bytes == 12
vstring bytes == 12

vbool capacity == 64
vint capacity == 33
vdouble capacity == 33
vstring capacity == 33

论坛徽章:
5
狮子座
日期:2013-08-20 10:12:24午马
日期:2013-11-23 18:04:102015年辞旧岁徽章
日期:2015-03-03 16:54:152015亚冠之德黑兰石油
日期:2015-06-29 18:11:1115-16赛季CBA联赛之新疆
日期:2024-02-21 10:00:53
2 [报告]
发表于 2009-08-07 13:47 |只看该作者
sizeof是类的字节大小。因为vector里面就是一指针,因此应该都是一样的,但是vector<bool>据说是用bitset实现的,因此大小有点不一样。

因为这个原因,同时造成了剩下两点的差异,猜测为,bitset每次都保留2的整次方的空间供使用(也许并不是这样,也许只是32的整数倍的空间:int v_[N];这种)。所以33超过了32,下面一个无论是哪种解释,都是64。而其他的在有初始值的时候,是严格地分配必要空间的。

而因为初始值指定了大小的缘故,三个的size都是一样大的。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP