resize()与reserve()都是vector容器中的方法:
resize():改变了capacity()和size()
reserve():增加了vector的capacity(),但是它的size()没有改变
#include <iostream>
#include <stdio.h>
#include <vector>
#include<functional>
using namespace std;
int main(int argc, char* argv[])
{
vector<int> v;
vector<int>::iterator it;
vector<int> v2;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(11);
v.push_back(12);
v.push_back(13);
v.push_back(14);
v2.push_back(21);
v2.push_back(22);
v2.push_back(23);
v2.push_back(24);
v2.push_back(25);
v2.push_back(26);
v2.push_back(27);
v2.push_back(28);
cout << "original data v:" << "===========start============" << "\n";
for (it = v.begin(); it != v.end(); ++it) {
cout << *it << endl;
}
cout << "original data v:" << "============end===========" << "\n";
cout << "original data v:" << ": capacity()=" << v.capacity() << ", size()=" << v.size() << "\n";
v.resize(10); //改变capacity()和size()
cout << "after resize data" << ": capacity()=" << v.capacity() << ", size()=" << v.size() << "\n";
for (it = v.begin(); it != v.end(); ++it) {
cout << *it << endl;
}
cout << "original data v2:" << "===========start============" << "\n";
for (it = v2.begin(); it != v2.end(); ++it) {
cout << *it << endl;
}
cout << "original data v2:" << "============end===========" << "\n";
cout << "original data v2:" << ": capacity()=" << v2.capacity() << ", size()=" << v2.size() << "\n";
v2.reserve(10); //只增加了capacity()
cout << "after reserve data" << ": capacity()=" << v2.capacity() << ", size()=" << v2.size() << "\n";
return 0;
}
根据上面的打印可以看出:
vector.resize():改变了capacity()和size()
vector.reserve():增加了vector的capacity(),但是它的size()没有改变