C++ STL 中 forward_list max_size() 函数及示例


本任务演示 C++ STL 中 forward_list max_size() 函数的工作原理。

什么是前向列表?

前向列表可以理解为单向链表,只能向前遍历,不能向后遍历,而列表则可以双向遍历,即元素包含两个链接,一个指向前一个元素,另一个指向后一个元素。因此,前向列表速度较快,因为它们只需要保存一个指向前一个元素的链接。可以在常数时间内插入和删除前向列表中的元素。

什么是 forward_list max_size() 函数?

forward_list::reverse( ) 是 C++ 标准模板库 (STL) 中的一个函数,用于反转前向列表中元素的顺序。

语法

forwardlist_name.reverse( )

参数

此函数没有任何参数。

返回值

此函数没有任何返回值。它只执行反转列表的操作。

例如

Input-: List of elements are: 57 99 54 34 84
Output–: Reversed elements of list are: 84 34 54 99 57
Input-: List of elements are: 40 30 60 90 70
Output–: Reversed elements of list are: 70 90 60 30 40

下面程序中使用的步骤如下

  • 首先初始化列表

  • 然后,我们在应用 reverse() 函数之前打印前向列表。

  • 然后,我们定义了 C++ 头文件中存在的 forward.reverse() 函数。

  • 然后,我们将显示反转后的前向列表

示例

/* 在下面的代码中,我们创建了一个前向列表并将元素插入到列表中。现在,任务是使用 max_size() 函数检查插入元素后前向列表的大小 */

 在线演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   //creating forward list
   forward_list<int> myForwardList;
   //add values to forward list
   myForwardList.assign(3, 2);
   cout << "The elements in my forward list are : ";
   for (auto i=myForwardList.begin(); i!=myForwardList.end();i++)
      cout << *i << " ";
   cout << "\nThe size of my Forward List is: " << myForwardList.max_size();
   return 0;
}

输出

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

The elements in my forward list are : 2 2 2
The size of my Forward List is:
1152921504606846975

示例

/* 在下面的代码中,我们创建了一个前向列表。现在,任务是使用 max_size() 函数检查前向列表的大小。 */

 在线演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   // creating forward list
   forward_list<int> myForwardList;
   cout << "\nsize of my forward list is: "<<myForwardList.max_size();
   return 0;
}

输出

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

size of my forward list is: 1152921504606846975

更新于: 2020-03-02

93 次浏览

开启你的 职业生涯

完成课程获得认证

立即开始
广告

© . All rights reserved.