當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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


相關用法


注:本文由純淨天空篩選整理自imdhruvgupta大神的英文原創作品 list insert() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。