C++ STL 中的 forward_list::push_front() 和 forward_list::pop_front()

c++server side programmingprogramming更新于 2025/4/23 6:07:17

在本文中,我们将讨论 C++ 中 forward_list::push_front() 和 forward_list::pop_front() 函数的工作原理、语法和示例。

STL 中的 Forward_list 是什么?

前向列表是序列容器,允许在序列中的任何位置进行常量时间插入和删除操作。前向列表实现为单链表。顺序由每个元素与序列中下一个元素的链接关联来保持。

什么是 forward_list::push_front()?

forward_list::push_front() 是 C++ STL 中的内置函数,在头文件中声明。 push_front() 用于将元素或值推送/插入到 forward_list 的前面或开头。当我们使用此函数时,容器中已有的第一个元素将成为第二个,推送的元素将成为 forward_list 容器的第一个元素,容器的大小增加 1。

语法

flist_container1.push_front (const value_type& value );

此函数只能接受一个参数,即要在开头插入的值。

返回值

此函数不返回任何内容。

push_front()

示例

在下面的代码中,我们使用 push_front() 操作将元素插入列表的前面,然后使用 sort() 函数对列表元素进行排序。

#include <forward_list>
#include <iostream>
using namespace std;
int main(){
   forward_list<int> forwardList = {12, 21, 22, 24};
   //使用 push_front() 函数在列表前面插入元素
   forwardList.push_front(78);
   cout<<"Forward List contains: ";
   for (auto i = forwardList.begin(); i != forwardList.end(); ++i)
      cout << ' ' << *i;
   //应用排序操作后的列表
   forwardList.sort();
   cout<<"\nForward List after performing sort operation : ";
   for (auto i = forwardList.begin(); i != forwardList.end(); ++i)
      cout << ' ' << *i;
}

输出

如果我们运行上述代码,它将生成以下输出

Forward List contains: 78 12 21 22 24
Forward List after performing sort operation : 12 21 22 24 78

什么是 forward_list::pop_front()?

forward_list::pop_front() 是 C++ STL 中的一个内置函数,在 <forward_list> 头文件中声明。pop_front() 用于弹出/删除位于 forward_list 开头的元素。当我们使用此函数时,容器中的第一个元素将被删除,第一个元素的下一个元素将成为 forward_list 容器的第一个元素,容器的大小减少 1。

语法

flist_container1.pop_front ();

此函数不接受任何参数

返回值

此函数不返回任何内容。

pop_front()

示例

在下面的代码中,我们使用 C++ STL 中的 pop_front() 操作删除列表的第一个元素。

#include <forward_list>
#include <iostream>
using namespace std;
int main(){
   forward_list<int> forwardList = {10, 20, 30 };
   //应用弹出操作之前的列表
   cout<<"执行弹出操作前的列表:";
   for(auto i = forwardList.begin(); i != forwardList.end(); ++i)
      cout << ' ' << *i;
   //应用弹出操作后的列表
   cout<<"\执行弹出操作后的列表: ";
   forwardList.pop_front();
   for (auto j = forwardList.begin(); j != forwardList.end(); ++j)
      cout << ' ' << *j;
}

输出

如果我们运行上述代码,它将生成以下输出

执行弹出操作前的列表:10 20 30
执行弹出操作后的列表:20 30

相关文章