qfedu-cpp-level/day9/stl_vector_demo/d11.cpp

36 lines
715 B
C++
Raw Permalink Normal View History

// vector 的删除操作
#include <bits/stdc++.h>
using namespace std;
template <typename T>
void print(vector<T> &v)
{
typename vector<T>::iterator it = v.begin();
while (it != v.end())
{
cout << *it << " ";
it++;
}
cout << endl;
}
int main()
{
int arr1[5] = {1, 2, 3, 4, 5};
vector<int> v1(arr1, arr1 + 5);
print(v1);
vector<int>::iterator it = v1.begin();
v1.insert(it, 1, 10); // 在 it 位置插入 1 个 10
print(v1);
v1.resize(0); // 缩小
vector<int>(v1).swap(v1); // 重新分配内存
print(v1);
cout << "size: " << v1.size() << " capacity: " << v1.capacity() << endl; // size: 2 capacity: 8
return 0;
}