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

35 lines
657 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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);
vector<int>::iterator it2 = v1.begin();
v1.insert(it2, 2, 9); // 在 it 位置插入 2 个 9之前的元素会向后移动
print(v1);
return 0;
}