zoukankan      html  css  js  c++  java
  • C++:STL vector:sizeof(vector)

    原文地址:http://blog.csdn.net/zcsylj/article/details/7857009

    int的大小是4,定义vector<int> vec,vec中有一个元素,sizeof(vec)=20,如果有1000个元素,则sizeof(vec)是多少?

     1 #include <iostream>  
     2 #include <vector>  
     3 using namespace std;  
     4 int main()  
     5 {  
     6      vector<int> vec;  
     7      for(int i=0;i<100;i++)  
     8      {  
     9         vec.push_back(i);  
    10         cout<<sizeof(vec)<<endl;   
    11         cout<<vec.size()<<endl;  
    12      }   
    13 }  

    输出结果:

    1 20  
    2 1  
    3 ……  
    4 20  
    5 100  
    6 请按任意键继续. . .  

    由此可以看出:sizeof(vec)只取决于vector里面存放的数据类型,与元素个数无关。该值应该是与编译器相关的。

     1 #include <iostream>  
     2 #include <vector>  
     3 using namespace std;  
     4 int main()  
     5 {  
     6     cout<<"sizeof(vector<char>) = "<<sizeof(vector<char>)<<endl;  
     7     cout<<"sizeof(vector<int>) = "<<sizeof(vector<int>)<<endl;  
     8     cout<<"sizeof(vector<short>) = "<<sizeof(vector<short>)<<endl;  
     9     cout<<"sizeof(vector<double>) = "<<sizeof(vector<double>)<<endl;  
    10     cout<<"sizeof(vector<long>) = "<<sizeof(vector<long>)<<endl;  
    11     cout<<"sizeof(vector<float>) = "<<sizeof(vector<float>)<<endl;  
    12     cout<<"sizeof(vector<bool>) = "<<sizeof(vector<bool>)<<endl;  
    13     cout<<"sizeof(vector<string>) = "<<sizeof(vector<string>)<<endl;  
    14 }  

    输出:

    1 sizeof(vector<char>) = 20  
    2 sizeof(vector<int>) = 20  
    3 sizeof(vector<short>) = 20  
    4 sizeof(vector<double>) = 20  
    5 sizeof(vector<long>) = 20  
    6 sizeof(vector<float>) = 20  
    7 sizeof(vector<bool>) = 28  
    8 sizeof(vector<string>) = 20  
    9 请按任意键继续. . .  

    解释:
    vector应该是从堆上分配内存,所有大小与元素个数无关

    sizeof(vector)取决于vector类的具体实现,STL是个完全开放的东西,谁都可以来实现vector类。

    通过查看STL源码可以看到vector有四个成员变量 
    _A   allocator; 
    iterator   _First,   _Last,   _End; 

    每个指针是4个字节,因此16字节。20字节的是不是添加了什么指针呢

  • 相关阅读:
    C# 图片与Base64的相互转化
    LeetCode 303. Range Sum Query – Immutable
    LeetCode 300. Longest Increasing Subsequence
    LeetCode 292. Nim Game
    LeetCode 283. Move Zeroes
    LeetCode 279. Perfect Squares
    LeetCode 268. Missing Number
    LeetCode 264. Ugly Number II
    LeetCode 258. Add Digits
    LeetCode 257. Binary Tree Paths
  • 原文地址:https://www.cnblogs.com/lzhu/p/6940528.html
Copyright © 2011-2022 走看看