vector大小

简单的程序,测试vector的大小[c++]:

#include <iostream.h>
#include <vector>

using namespace std;

struct Node
{
	int id;
	vector<int> score;
};

void DisplayVector(vector<int> &v)
{
	cout<<"sizeof(v) = "<<sizeof(v)<<endl;
	for(vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout<<*it<<'\t';
	}
	cout<<endl;
}

void DisplaySize()
{
	cout<<"sizeof(vector<char>) = "<<sizeof(vector<char>)<<endl;
	cout<<"sizeof(vector<int>) = "<<sizeof(vector<int>)<<endl;
	cout<<"sizeof(vector<short>) = "<<sizeof(vector<short>)<<endl;
	cout<<"sizeof(vector<double>) = "<<sizeof(vector<double>)<<endl;
	cout<<"sizeof(vector<long>) = "<<sizeof(vector<long>)<<endl;
	cout<<"sizeof(vector<float>) = "<<sizeof(vector<float>)<<endl;
}

int main()
{
	DisplaySize();

	Node node;
	cout<<"sizeof(Node) = "<<sizeof(node)<<endl;

	node.id = 1;
	node.score.push_back(10);
	node.score.push_back(20);
	node.score.push_back(25);
	cout<<"sizeof(Node) = "<<sizeof(node)<<endl;

	DisplayVector(node.score);

	return 0;
}

输出结果:

sizeof(vector<char>) = 16
sizeof(vector<int>) = 16
sizeof(vector<short>) = 16
sizeof(vector<double>) = 16
sizeof(vector<long>) = 16
sizeof(vector<float>) = 16
sizeof(Node) = 20
sizeof(Node) = 20
sizeof(v) = 16
10      20      25

修改了下主函数:

int main()
{
 DisplaySize();

 Node node;
 cout<<"sizeof(Node)_1 = "<<sizeof(node)<<endl;

 node.id = 1;
 for(int i = 1; i <= 1000; i++)
 {
  node.score.push_back(i);
 }
 cout<<"sizeof(Node)_2 = "<<sizeof(node)<<endl; // 不管插入多少数据,sizeof(vector<>)大小不变

// DisplayVector(node.score);

 return 0;
}

发现“不管插入多少数据,sizeof(vector<>)大小不变,始终为16”!

posted on 2011-02-14 12:57  清清飞扬  阅读(2744)  评论(0编辑  收藏  举报