转载自http://blog.csdn.net/linhao19841211_2/article/details/8154805
reserve和resize是vector里两个很重要的方法,有效地使用这两个方法可以减少reallocate memory的次数,提高程序的性能,所以还是有必要去研究一下的,先来看一段简单的代码吧。
stdafx.h
[html] view plain copy // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #include <stdio.h> #include <tchar.h> // TODO: reference additional headers your program requires here #include <iostream> #include <vector> #include <string> using namespace std;test.cpp
[cpp] view plain copy // test.cpp : Defines the entry point for the console application. // #include "stdafx.h" class A { public: A() : m_a(0) { } A(int a) : m_a(a) { } A(const A& a) : m_a(a.m_a) { } ~A() { } private: int m_a; }; int _tmain(int argc, _TCHAR* argv[]) { vector<A> myVec; myVec.reserve(100); cout << "capacity:" << myVec.capacity() << endl; cout << "size:" << myVec.size() << endl; for (int i = 0; i < 100; i++) { myVec.push_back(i); } cout << "capacity:" << myVec.capacity() << endl; cout << "size:" << myVec.size() << endl; myVec.resize(102); myVec[100] = 1; myVec[101] = 2; cout << "capacity:" << myVec.capacity() << endl; cout << "size:" << myVec.size() << endl; return 0; }输出:
reserve用来(预留空间,)改变capacity,不改变size,会去分配内存,但不会构造出对象;如果改变后的capacity比当前capacity大,则capacity会变大;反之,capacity不变。可以用下面的代码去测试:
[cpp] view plain copy vector<A> myVec; myVec.reserve(100); cout << "capacity:" << myVec.capacity() << endl; cout << "size:" << myVec.size() << endl; myVec.reserve(90); cout << "capacity:" << myVec.capacity() << endl; cout << "size:" << myVec.size() << endl; myVec.reserve(110); cout << "capacity:" << myVec.capacity() << endl; cout << "size:" << myVec.size() << endl;输出:
resize用来改变vector的size,有可能也会改变capacity。如果改变后的size比当前capacity大,则capacity会变大,同时构造出多出来的对象;反之,capacity不变,同时析构一些不再需要的对象。可以用下面的代码去测试:
[cpp] view plain copy vector<A> myVec; myVec.resize(100); cout << "capacity:" << myVec.capacity() << endl; cout << "size:" << myVec.size() << endl; myVec.resize(90); cout << "capacity:" << myVec.capacity() << endl; cout << "size:" << myVec.size() << endl; myVec.resize(110); cout << "capacity:" << myVec.capacity() << endl; cout << "size:" << myVec.size() << endl;输出:
reserve和resize都不会使capacity变小,但都有可能使capacity变大,具体怎么变大,reserve和resize是不一样的,reserve能准确控制capacity;而resize不能,vc里是每次增大一半的当前capacity。可以用下面的代码去测试不用reserve和resize的情况(在这种情况下,每当capacity不够时,就会去allocate一块新的够大的内存,再释放以前的内存,效率是很低的):
[cpp] view plain copy vector<A> myVec; cout << "capacity:" << myVec.capacity() << endl; cout << "size:" << myVec.size() << endl; for (int i = 0; i < 100; i++) { myVec.push_back(i); cout << "capacity:" << myVec.capacity() << endl; cout << "size:" << myVec.size() << endl; }输出:
