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

37 lines
816 B
C++

#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<double> v1(arr1, arr1 + 5);
v1.resize(10, 9); // 重新指定容器的长度,并用9填充
print(v1);
vector<int> v2;
v2.reserve(3); // 预留足够的空间避免频繁扩容导致的首地址变化
// v2.resize(2); // resize 也可以预留空间,但是不会填充
v2.push_back(1);
cout << "first addr: " << &v2[0] << endl;
v2.push_back(2);
cout << "first addr: " << &v2[0] << endl;
v2.push_back(3);
cout << "first addr: " << &v2[0] << endl;
return 0;
}