• CentOS 4.6 x86_64 g++ 3.4.6 中vector的Grow策略


    写了一个小程序,测试了一下vector是如何分配内存的:

    Code: Select all
    #include <iostream>
    #include <vector>
    #include <string>
    using namespace std;

    int main()
    {
        vector<string> vec1;
        cout << "Vector size is:  " << vec1.size() << ", capacity is: " << vec1.capacity() << endl;

        for (int i=0; i<30; i++) {
            vec1.push_back("String 1");
            cout << "Vector size is:  " << vec1.size() << ", capacity is: " << vec1.capacity() << endl;
        }

        vec1.reserve(50);
        vec1.push_back("String 2");
        vec1.push_back("String 3");
        cout << "Vector size is:  " << vec1.size() << ", capacity is: " << vec1.capacity() << endl;

        return 0;
    }


    程序的输出是:

    Vector size is: 0, capacity is: 0
    Vector size is: 1, capacity is: 1
    Vector size is: 2, capacity is: 2
    Vector size is: 3, capacity is: 4
    Vector size is: 4, capacity is: 4
    Vector size is: 5, capacity is: 8
    Vector size is: 6, capacity is: 8
    Vector size is: 7, capacity is: 8
    Vector size is: 8, capacity is: 8
    Vector size is: 9, capacity is: 16
    Vector size is: 10, capacity is: 16
    Vector size is: 11, capacity is: 16
    Vector size is: 12, capacity is: 16
    Vector size is: 13, capacity is: 16
    Vector size is: 14, capacity is: 16
    Vector size is: 15, capacity is: 16
    Vector size is: 16, capacity is: 16
    Vector size is: 17, capacity is: 32
    Vector size is: 18, capacity is: 32
    Vector size is: 19, capacity is: 32
    Vector size is: 20, capacity is: 32
    Vector size is: 21, capacity is: 32
    Vector size is: 22, capacity is: 32
    Vector size is: 23, capacity is: 32
    Vector size is: 24, capacity is: 32
    Vector size is: 25, capacity is: 32
    Vector size is: 26, capacity is: 32
    Vector size is: 27, capacity is: 32
    Vector size is: 28, capacity is: 32
    Vector size is: 29, capacity is: 32
    Vector size is: 30, capacity is: 32
    Vector size is: 32, capacity is: 50

    所以,可以看出,这个平台上,vector的内存分配策略是1, 2, 4, 8, 16, 32......
    g++的版本信息是:
    g++ (GCC) 3.4.6 20060404 (Red Hat 3.4.6-9)
  • 相关阅读:
    linux 命令——48 watch (转)
    linux 命令——47 iostat (转)
    linux 命令——46 vmstat(转)
    linux 命令——45 free(转)
    linux 命令——44 top (转)
    linux 命令——43 killall(转)
    linux 命令——42 kill (转)
    linux 命令——41 ps(转)
    linux 命令——40 wc (转)
    Java for LeetCode 068 Text Justification
  • 原文地址:https://www.cnblogs.com/super119/p/1996150.html
Copyright © 2020-2023  润新知