c++ 将容量设置为容器的长度(shrink_to_fit)
#include <iostream> #include <vector> using namespace std; int main () { vector<int> myvector (25); cout << "1. capacity of myvector: " << myvector.capacity() << '\n'; for (int i=0; i<20; i++) myvector[i]=i; myvector.resize(10); cout << "2. capacity of myvector: " << myvector.capacity() << '\n'; for (int i=0; i<25; i++) cout << myvector[i]<<endl; cout<<"\n"<<endl; myvector.shrink_to_fit(); for (int i=0; i<10; i++) cout << myvector[i]<<endl; cout << "3. capacity of myvector: " << myvector.capacity() << '\n'; return 0; }