vector :: insert()是“ vector”标头的库函数,用于在向量中插入元素,它接受一个元素,具有默认值或其他容器中其他值的元素集,并从指定的迭代器位置。
注意:要使用向量,请包含<vector>标头。
vector :: insert()函数的语法
//插入元素 vector::insert(iterator position, value); //插入多个元素 vector::insert(iterator position, size, default_value); //从其他容器插入元素 vector::insert(iterator position, iterator start_position, iterator end_position);
参数:
在插入元素的情况下:迭代器位置,值–迭代器位置是使用向量的迭代器的索引,其中要添加元素的值是元素。
在插入多个元素的情况下:迭代器位置,大小,default_value –迭代器位置是使用要添加元素的向量的迭代器的索引,大小是要添加的元素数,并且default_value是要插入的值向量。
对于从其他容器插入元素的情况:迭代器位置,迭代器start_position,迭代器end_position –迭代器位置是使用要添加元素的向量的迭代器的索引,start_position,迭代器end_position是要插入其值的另一个容器的迭代器在当前向量中。
返回值:
在插入一个元素的情况下,它返回一个指向第一个新添加的元素的迭代器,在其他情况下,它返回void。
示例
    Input:
    //向量声明
    vector<int> v1{ 10, 20, 30, 40, 50 };
    //数组
    int x[] = { 1, 2, 3, 4, 5 };
    
    //插入元素
    v1.insert(v1.begin() + 2, 100); //在第二个索引处插入100-
    
    //插入多个元素 with default value
    //从第二个索引插入5个元素(99)
	v1.insert(v1.begin() + 2, 5, 99);     
    //插入数组(其他容器元素)
    
    //从第一个索引插入3个元素(来自数组)
	v1.insert(v1.begin() + 1, x + 0, x + 3); 
    
    Output:
    v1: 10 1 2 3 20 99 99 99 99 99 100 30 40 50//C ++ STL程序演示示例
//vector :: insert()函数
#include <iostream>
#include <vector>
using namespace std;
int main(){
    //向量声明
    vector<int> v1{ 10, 20, 30, 40, 50 };
    //数组
    int x[] = { 1, 2, 3, 4, 5 };
    //打印元素
    cout << "before inserting the elements..." << endl;
    cout << "size of v1: " << v1.size() << endl;
    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;
    //插入元素
    v1.insert(v1.begin() + 2, 100); //在第二个索引处插入100-
    //打印元素
    cout << "after inserting an element..." << endl;
    cout << "size of v1: " << v1.size() << endl;
    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;
    //插入多个元素 with default value
    //从第二个索引插入5个元素(99)
    v1.insert(v1.begin() + 2, 5, 99);
    //打印元素
    cout << "after inserting multiple elements..." << endl;
    cout << "size of v1: " << v1.size() << endl;
    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;
    //插入数组(其他容器元素)
    //从第一个索引插入3个元素(来自数组)
    v1.insert(v1.begin() + 1, x + 0, x + 3);
    //打印元素
    cout << "after inserting multiple elements..." << endl;
    cout << "size of v1: " << v1.size() << endl;
    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;
    return 0;
}输出结果
before inserting the elements... size of v1: 5 v1: 10 20 30 40 50 after inserting an element... size of v1: 6 v1: 10 20 100 30 40 50 after inserting multiple elements... size of v1: 11 v1: 10 20 99 99 99 99 99 100 30 40 50 after inserting multiple elements... size of v1: 14 v1: 10 1 2 3 20 99 99 99 99 99 100 30 40 50
参考:C ++ vector :: insert()