C++ STL 中的 forward_list::front() 和 forward_list::empty()


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

什么是 STL 中的 Forward_list?

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

什么是 forward_list::front()?

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

语法

forwardlist_container.front();

此函数不接受任何参数。

返回值

此函数返回指向容器第一个元素的迭代器。

示例

/* 在下面的代码中,我们创建一个 forward list 并向其中插入元素,然后我们将调用 front() 函数来获取 forward list 中的第一个元素。 */

 在线演示

#include <forward_list>
#include <iostream>
using namespace std;
int main(){
   forward_list<int> forwardList = {2, 6, 1, 0 };
   cout<<"my first element in a forward list is: ";
   cout<<forwardList.front();
   return 0;
}

输出

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

my first element in a forward list is: 2

什么是 forward_list::empty()?

forward_list::empty() 是 C++ STL 中一个内置函数,声明在 <forward_list> 头文件中。如果 forward list 容器为空,empty() 返回 true,否则返回 false。此函数检查容器的大小是否为 0。

语法

bool forwardlist_container.empty();

此函数不接受任何参数。

返回值

如果容器的大小为 0,此函数返回 true,否则返回 false。

示例

/* 在下面的代码中,我们创建一个 forward list,然后我们将通过调用 empty() 函数来检查列表是否为空。之后,我们将向 forward list 插入元素,然后我们将再次调用 empty() 函数来检查结果。 */

 在线演示

#include <forward_list>
#include <iostream>
using namespace std;
int main(){
   forward_list<int> forwardList = {};
   if (forwardList.empty()){
      cout << "Yess forward list is empty\n";
   }
   forwardList = {1, 3, 4, 5};
   if (forwardList.empty()){
      cout << "Yess forward list is empty\n";
   } else {
      cout << "No forward list is not empty\n";
   }
   return 0;
}

输出

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

Yess forward list is empty
No forward list is not empty

更新于:2020年3月2日

119 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.