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
相關用法
- C++ map insert()用法及代碼示例
- C++ unordered_map insert用法及代碼示例
- C++ std::string::insert()用法及代碼示例
- C++ multimap insert()用法及代碼示例
- C++ set insert()用法及代碼示例
- C++ unordered_multimap insert()用法及代碼示例
- C++ unordered_multiset insert()用法及代碼示例
- C++ vector insert()用法及代碼示例
- C++ multiset insert()用法及代碼示例
- C++ unordered_set insert()用法及代碼示例
- C++ deque insert()用法及代碼示例
注:本文由純淨天空篩選整理自imdhruvgupta大神的英文原創作品 list insert() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。