c++的insert函数
时间: 2023-12-16 07:02:29 浏览: 43
C++的`insert()`函数用于在容器中的指定位置插入一个或多个元素。其语法如下:
```c++
iterator insert (iterator position, const value_type& val);
void insert (iterator position, size_type n, const value_type& val);
template <class InputIterator>
void insert (iterator position, InputIterator first, InputIterator last);
```
其中,第一个函数用于插入单个元素,第二个函数用于插入n个相同的元素,第三个函数用于插入由迭代器指定范围内的元素。
示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v = {1, 2, 3, 4};
// 在指定位置插入单个元素
auto it = v.begin() + 2;
v.insert(it, 5);
// 在指定位置插入n个相同元素
it = v.begin() + 1;
v.insert(it, 3, 6);
// 在指定位置插入由迭代器指定范围内的元素
vector<int> v2 = {7, 8, 9};
it = v.begin() + 4;
v.insert(it, v2.begin(), v2.end());
// 输出结果
for (auto i : v) {
cout << i << " ";
}
return 0;
}
```
输出结果为:`1 6 6 6 7 8 9 5 2 3 4`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)