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
#include // for list operations
using namespace std;
int main()
{
// declaring list
list list1;
// using assign() to insert multiple numbers
// creates 3 occurrences of "2"
list1.assign(3, 2);
// initializing list iterator to beginning
list::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::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::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++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。