代码

  1. #include<iostream>
  2. #include<vector>
  3. using namespace std;
  4. //vector的容量和大小操作
  5. //函数原型
  6. /*
  7. ① empty(); //判断容器是否为空
  8. ② capacity(); //容器的容量
  9. ③ size(); //返回容器中元素的个数
  10. ④ resize(int num); //重新指定容器的长度为num,若容器变长,则默认值填充新位置;
  11. //如果容器变短,则末尾超出容器长度的元素被删除。
  12. ⑤ resize(int num,elem); //重新指定容器的长度为num,若容器变长,则elem填充新位置;
  13. //如果容器变短,则末尾超出容器长度的元素被删除。
  14. */
  15. void printVector(vector<int>& v) {
  16. for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
  17. cout << *it << " ";
  18. }
  19. cout << endl;
  20. }
  21. void test01(){
  22. vector<int>v1;
  23. for (int i = 0; i < 10; i++) {
  24. v1.push_back(i);
  25. }
  26. printVector(v1);
  27. //①②③
  28. if (v1.empty()) {
  29. cout << "v1为空" << endl;
  30. }
  31. else {
  32. cout << "v1不为空" << endl;
  33. cout << "v1的容量为:" << v1.capacity()<<endl;
  34. cout << "v1的大小为:" << v1.size() << endl;
  35. }
  36. //④重新指定大小
  37. //填充值只会填充扩增的元素位置
  38. v1.resize(15);
  39. printVector(v1);//如果重新指定的比原来长,默认用0填充新的位置。
  40. v1.resize(18, 100);
  41. printVector(v1);//利用重载版本,指定默认填充值。
  42. //减小容量
  43. v1.resize(5);
  44. printVector(v1);//如果重新指定的比原来短了,超出部分会删除掉。
  45. }
  46. int main() {
  47. test01();
  48. return 0;
  49. }

运行结果

image.png