C++ STL 中的 forward_list::before_begin()

c++server side programmingprogramming更新于 2025/4/23 15:52:17

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

STL 中的 Forward_list 是什么?

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

什么是 forward_list::before_begin()?

forward_list::before_begin() 是 C++ STL 中的内置函数,在 <forward_list> 头文件中声明。 before_begin() 返回指向 forward_list 容器中第一个元素之前的元素的迭代器。

语法

forwardlist_container.before_begin();

此函数不接受任何参数。

返回值

此函数返回指向序列开头之前位置的迭代器。

示例

/* 在下面的代码中,我们创建一个前向列表,然后使用 before_begin() 函数指向前向列表中的第一个元素,之后我们将尝试使用 insert_after() 函数在前向列表前面插入一个新元素。现在,我们将注意到输出中的变化。 */

#include <bits/stdc++.h>
using namespace std;
int main() {
   //创建并初始化转发列表
   forward_list<int> forwardList = { 3, 6, 1, 2, 4 };
   //调用 before_begin 函数
   auto i = forwardList.before_begin();
   //在转发列表前插入元素
   forwardList.insert_after(i, 7);
   cout<< "Element of the forward list are:" << endl;
   for (auto j = forwardList.begin(); j != forwardList.end(); ++j)
      cout << *j << " ";
   return 0;
}

输出

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

Element of the forward list are:
7 3 6 1 2 4

示例

#include <bits/stdc++.h>
using namespace std;
int main() {
   forward_list<int> forwardList = {2, 23, 12, 11};
   forwardList.insert_after(forwardList.before_begin(), 19 );
   cout << "Elements in the forward lists are : ";
   for (auto j = forwardList.begin(); j != forwardList.end(); ++j)
      cout << *j << " ";
   return 0;
}

输出

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

Elements in the forward lists are : 19 2 23 12 11

相关文章