C++ STL 中的 list::pop_front() 和 list::pop_back()
在本文中,我们将讨论 C++ STL 中 list::pop_front() 和 list::pop_back() 函数的工作原理、语法和示例。
什么是 STL 中的列表?
列表是一种数据结构,允许在序列中的任何位置进行常数时间插入和删除。列表以双向链表的形式实现。列表允许非连续内存分配。与数组、向量和双端队列相比,列表在容器的任何位置执行元素的插入、提取和移动方面表现更好。在列表中,对元素的直接访问速度很慢,并且列表类似于 forward_list,但 forward_list 对象是单向链表,它们只能向前迭代。
什么是 forward_list::pop_front()?
list::pop_front() 是 C++ STL 中的一个内置函数,它在头文件中声明。pop_front() 用于弹出/删除列表开头的元素。当我们使用此函数时,容器中已存在的第一个元素将被删除,第一个元素的下一个元素将成为列表容器的第一个元素,并且容器的大小将减少 1。
语法
list_container1.pop_front ();
参数
此函数不接受任何参数。
返回值
此函数不返回任何内容。
示例
Input: list<int> List_container= {10, 11, 13, 15};
List_container.pop_front();
Output:
List = 11 13 15示例
#include <iostream>
#include <list>
using namespace std;
int main(){
list<int> myList_1 = {}, myList_2 = {};
myList_1.push_front(10);
myList_1.push_front(20);
myList_1.push_front(30);
myList_1.push_front(40);
myList_1.push_front(50);
while (!myList_1.empty()){
myList_2.push_front(myList_1.front());
myList_1.pop_front();
}
cout<<"Elements in the list are : ";
for (auto i = myList_2.begin(); i!= myList_2.end(); ++i)
cout << ' ' << *i;
}输出
如果我们运行以上代码,它将生成以下输出:
Elements in the list are : 10 20 30 40 50
什么是 list::pop_back()?
list::pop_back() 是 C++ STL 中的一个内置函数,它在头文件中声明。pop_back() 用于从列表容器的末尾或最后一个位置删除/弹出元素。当我们使用 pop_back 时,它会删除/弹出最后一个元素,最后一个元素之前的元素将成为最后一个元素,并且列表容器的大小将减少 1。
语法
list_container.pop_back();
参数
此函数不接受任何参数。
返回值
此函数不返回任何内容。
示例
Input: list<int> List_container= {10, 11, 13, 15};
List_container.pop_back();
Output:
List = 10 11 13示例
#include <iostream>
#include <list>
using namespace std;
int main(){
list<int> myList_1 = {}, myList_2 = {};
myList_1.push_front(10);
myList_1.push_front(20);
myList_1.push_front(30);
myList_1.push_front(40);
myList_1.push_front(50);
while (!myList_1.empty()){
myList_2.push_front(myList_1.back());
myList_1.pop_back();
}
cout<<"Elements in the list are : ";
for (auto i = myList_2.begin(); i!= myList_2.end(); ++i)
cout << ' ' << *i;
}输出
如果我们运行以上代码,它将生成以下输出:
Elements in the list are : 50 40 30 20 10
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP