STL源码剖析笔记(vector)
程序员文章站
2022-03-23 11:34:00
...
vector内部是在初始化的时候申请一段连续内存空间,需要加入元素时,若当前已经申请的空间足够新元素使用,则直接将新元素放在内存中,若不够用的话,就在动态申请新的一块内存,新内存大小为:min(当前已申请的内存*2,当前已申请的内存+新元素所占内存),然后将原来的数据从旧内存复制到新内存中去,释放旧内存空间,将新加入的元素放入新内存中,初学者可通过vector.size()和vector.capacity()来验证
int main()
{
vector<int> ve;
for(int i=0;i<10;i++){
cout<<"size() = "<<ve.size()<<endl;
cout<<"capacity() = "<<ve.capacity()<<endl;
ve.push_back(i);
}
return 0;
}
output:
size() = 0
capacity() = 0
size() = 1
capacity() = 1
size() = 2
capacity() = 2
size() = 3
capacity() = 4
size() = 4
capacity() = 4
size() = 5
capacity() = 8
size() = 6
capacity() = 8
size() = 7
capacity() = 8
size() = 8
capacity() = 8
size() = 9
capacity() = 16
因此,平常使用vector的时候,如果已经知道了vector要存储的最小元素数量x,则可直接创建x个元素,以节省耗时,以下举例说明:
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <deque>
#include <vector>
#include <ctime>
#include <windows.h>
using namespace std;
typedef long long ll;
const int maxn = 1e7+7;
const int mod = 1e9+7;
void func1()
{
double now1 = GetTickCount();//获取当前时间
vector<int> ve;
for(int i=0;i<maxn;i++){
ve.push_back(i);
}
double now2 = GetTickCount();
cout<<now2-now1<<endl;//输出时间差
}
void func2()
{
double now1 = GetTickCount();
vector<int> ve(maxn,0);
for(int i=0;i<maxn;i++){
ve[i]=i;
}
double now2 = GetTickCount();
cout<<now2-now1<<endl;
}
int main ()
{
func1();
func2();
return 0;
}
//output
//297
//78
上一篇: MVC模式
下一篇: STL源码剖析笔记(heap)