给定一个包含某些元素的列表,我们必须在C ++(STL)程序中,在列表的开头(开头)和后面(结尾)插入一个元素。
这是两个函数,可用于在列表的前面和结尾插入元素。push_front()将元素插入到前面,而push_back()将元素插入到后面(结束)。
让我们实现下面的程序...
示例
Input: List: [10, 20, 30, 40, 50] Element to insert at front: 100 Element to insert at back: 200 Output: List is: 100 10 20 30 40 50 200
程序:
#include <iostream>
#include <list>
#include <string>
using namespace std;
int main() {
//声明aiList-
list<int>iList = {10, 20, 30, 40, 50};
//在列表中声明迭代器
list<int>::iterator l_iter;
//在前面插入元素
iList.push_front(100);
//在后面插入元素
iList.push_back(200);
//打印列表元素
cout<<"List elements are"<<endl;
for (l_iter = iList.begin(); l_iter != iList.end(); l_iter++)
cout<< *l_iter<<endl;
return 0;
}输出结果
List elements are 100 10 20 30 40 50 200