C++ list insert()实例讲解

时间:2022-04-06
本文章向大家介绍C++ list insert()实例讲解,主要分析其语法、参数、返回值和注意事项,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

list::insert()用于在列表的任何位置插入元素。此函数需要3个元素,位置,要插入的元素数和要插入的值。如果未提及,则元素数默认设置为1。

用法:

insert(pos_iter, ele_num, ele)

参数:此函数接受三个参数:


  • pos_iter:在容器中插入新元素的位置。
  • ele_num:要插入的元素数。每个元素都初始化为val的副本。
  • ele:要复制(或移动)到插入元素的值。

返回值:此函数返回一个迭代器,该迭代器指向新插入的元素中的第一个。

// C++ code to demonstrate the working of 
// insert() function 
  
#include <iostream> 
#include <list> // for list operations 
using namespace std; 
  
int main() 
{ 
    // declaring list 
    list<int> list1; 
  
    // using assign() to insert multiple numbers 
    // creates 3 occurrences of "2" 
    list1.assign(3, 2); 
  
    // initializing list iterator to beginning 
    list<int>::iterator it = list1.begin(); 
  
    // iterator to point to 3rd position 
    advance(it, 2); 
  
    // using insert to insert 1 element at the 3rd position 
    // inserts 5 at 3rd position 
    list1.insert(it, 5); 
  
    // Printing the new list 
    cout << "The list after inserting"
         << " 1 element using insert() is : "; 
    for (list<int>::iterator i = list1.begin(); 
         i != list1.end(); 
         i++) 
        cout << *i << " "; 
  
    cout << endl; 
  
    // using insert to insert 
    // 2 element at the 4th position 
    // inserts 2 occurrences 
    // of 7 at 4th position 
    list1.insert(it, 2, 7); 
  
    // Printing the new list 
    cout << "The list after inserting"
         << " multiple elements "
         << "using insert() is : "; 
  
    for (list<int>::iterator i = list1.begin(); 
         i != list1.end(); 
         i++) 
        cout << *i << " "; 
  
    cout << endl; 
}
输出:
The list after inserting 1 element using insert() is : 2 2 5 2 
The list after inserting multiple elements using insert() is : 2 2 5 7 7 2