功能描述:
- 對vector容器的容量和大小操作
函數原型:
empty(); //判斷容器是否為空
capacity(); //容器的容量
size(); //返回容器中元素的個數
resize(int num); //重新指定容器的長度為num,若容器變長,則以默認值填充新位置
//如果容器變短,則末尾超出容器長度的元素被刪除
resize(int num, elem); //重新指定容器的長度為num,若容器變長,則以elem值填充新位置
//如果容器變短,則末尾超出容器長度的元素被刪除
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 5 void printVector(vector<int> &v) 6 { 7 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 8 { 9 cout << *it << " "; 10 } 11 cout << endl; 12 } 13 14 15 void test_01() 16 { 17 vector<int> v1; 18 for (int i = 0; i < 10; i++) 19 { 20 v1.push_back(i); 21 } 22 if (v1.empty()) 23 { 24 cout << "vector 容器空" << endl; 25 } 26 else 27 { 28 cout << "vector 容器非空" << endl; 29 printVector(v1); 30 cout << "vector 的容量為:" << v1.capacity() << endl; 31 cout << "vector 的大小為:" << v1.size() << endl; 32 } 33 34 //重新指定大小 35 v1.resize(15);//可以指定填充值,參數2 36 printVector(v1);//不指定參數2,默認填充0 37 38 } 39 40 int main(void) 41 { 42 test_01(); 43 44 system("pause"); 45 return 0; 46 47 }
