以下为试验程序:
#include <iostream>
#include <vector>
#include <string>
#include <cstddef>
using namespace std;
int main()
{
string word1 = "Teddy";
string word2 = "Bear";
vector<int> vec1{ 0,1,2,3,4 };
vector<int> vec2{ 0,1,2 };
vector<string> vec3 = { "Teddy","Bear" };
cout << "size of int is " << sizeof(int) << ".\n";
cout << "size of long is " << sizeof(long) << ".\n";
cout << "size of long long is " << sizeof(long long) << ".\n";
cout << "size of short is " << sizeof(short) << ".\n";
cout << "size of char is " << sizeof(char) << ".\n";
cout << "size of 'word1' is " << sizeof word1 << ".\n";
cout << "size of 'word2' is " << sizeof word2 << ".\n";
cout << "size of 'vec1' is " << sizeof vec1 << ".\n";
cout << "size of 'vec2' is " << sizeof vec2 << ".\n";
cout << "size of 'vec3' is " << sizeof vec3 << ".\n";
return 0;
}
我的电脑的output为:
(每台电脑不一定一样)
由规律知 vector,string 的 sizeof 值与存的内容无关。
此程序中未列数组的sizeof。数组的为每个元素的sizeof值乘上个数。