当增加新元素(s)时,如果超过当时的容量,则容量会扩充至两倍。如果两倍容量仍不足,就扩张至足够大的容量。
以一个例子来说明:
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { int i; vector<int> iv(2,9); cout<<"size = "<<iv.size()<<endl; cout<<"capacity = "<<iv.capacity()<<endl; iv.push_back(1); cout<<"size = "<<iv.size()<<endl; cout<<"capacity = "<<iv.capacity()<<endl; iv.push_back(2); cout<<"size = "<<iv.size()<<endl; cout<<"capacity = "<<iv.capacity()<<endl; iv.push_back(3); cout<<"size = "<<iv.size()<<endl; cout<<"capacity = "<<iv.capacity()<<endl; iv.push_back(4); cout<<"size = "<<iv.size()<<endl; cout<<"capacity = "<<iv.capacity()<<endl; for(i = 0;i < iv.size();i++) cout<<iv[i]<<" "; cout<<endl; iv.push_back(5); cout<<"size = "<<iv.size()<<endl; cout<<"capacity = "<<iv.capacity()<<endl; for(i = 0;i < iv.size();i++) cout<<iv[i]<<" "; cout<<endl; iv.pop_back(); iv.pop_back(); cout<<"size = "<<iv.size()<<endl; cout<<"capacity = "<<iv.capacity()<<endl; iv.pop_back(); cout<<"size = "<<iv.size()<<endl; cout<<"capacity = "<<iv.capacity()<<endl; vector<int>::iterator ivite = find(iv.begin(),iv.end(),1); if(ivite != iv.end()) iv.erase(ivite); cout<<"size = "<<iv.size()<<endl; cout<<"capacity = "<<iv.capacity()<<endl; for(i = 0;i < iv.size();i++) cout<<iv[i]<<" "; cout<<endl; ivite = find(iv.begin(),iv.end(),2); if(ivite != iv.end()) iv.insert(ivite,3,7); cout<<"size = "<<iv.size()<<endl; cout<<"capacity = "<<iv.capacity()<<endl; for(i = 0;i < iv.size();i++) cout<<iv[i]<<" "; cout<<endl; iv.clear(); cout<<"size = "<<iv.size()<<endl; cout<<"capacity = "<<iv.capacity()<<endl; return 0; }
时间: 2024-11-05 23:12:05