如何使用vector的reserve和resize方法
阿新 • • 發佈:2019-01-22
reserve和resize是vector裡兩個很重要的方法,有效地使用這兩個方法可以減少reallocate memory的次數,提高程式的效能,所以還是有必要去研究一下的,先來看一段簡單的程式碼吧。
stdafx.h
- // 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
- // 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不變。可以用下面的程式碼去測試:
- 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不變,同時析構一些不再需要的物件。可以用下面的程式碼去測試:
- 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一塊新的夠大的記憶體,再釋放以前的記憶體,效率是很低的):
- 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;
- }
輸出: