转发列表 在STL中实现了单链表。forward list是从C++11引入的,在插入、移除和移动操作(如排序)中,它比其他容器更有用,并且允许以时间常量插入和移除元素。它与list的不同之处在于,forward list只跟踪下一个元素的位置,而list同时跟踪下一个和上一个元素。
null
转发列表::前端()
此函数用于引用转发列表容器的第一个元素。此函数可用于获取转发列表的第一个元素。
语法:
forwardlistname.front()Parameters :No value is needed to pass as the parameter.Returns :Direct reference to the first element of the container.
例如:
Input : forward_list forwardlist{1, 2, 3, 4, 5}; forwardlist.front();Output : 1Input : forward_list forwardlist{0, 1, 2, 3, 4, 5}; forwardlist.front();Output : 0
错误和异常 1.如果转发列表容器为空,则会导致未定义的行为。 2.如果转发列表不为空,则具有无异常抛出保证。
C++
// CPP program to illustrate // Implementation of front() function #include <forward_list> #include <iostream> using namespace std; int main() { forward_list< int > myforwardlist{ 1, 2, 3, 4, 5 }; cout << myforwardlist.front(); return 0; } |
输出:
1
转发列表::空()
empty()函数用于检查转发列表容器是否为空。
语法:
forwardlistname.empty()Parameters :No parameters are passed.Returns :True, if list is emptyFalse, Otherwise
例如:
Input : forward_list forwardlist{1, 2, 3, 4, 5}; forwardlist.empty();Output : FalseInput : forward_list forwardlist{}; forwardlist.empty();Output : True
错误和异常 1.它有一个无例外的抛出保证。 2.传递参数时显示错误。
C++
// CPP program to illustrate // Implementation of empty() function #include <forward_list> #include <iostream> using namespace std; int main() { forward_list< int > myforwardlist{}; if (myforwardlist.empty()) { cout << "True" ; } else { cout << "False" ; } return 0; } |
输出:
True
应用程序–front()和empty(): 给定一个整数列表,求所有整数的和。
Input : 1, 5, 6, 3, 9, 2Output : 26Explanation - 1+5+6+3+9+2 = 26
算法: 1.检查转发列表是否为空,如果不是,则将前端元素添加到初始化为0的变量中,并弹出前端元素。 2.重复此步骤,直到转发列表为空。 3.打印变量的最终值。
C++
// CPP program to illustrate // Application of empty() function #include <forward_list> #include <iostream> using namespace std; int main() { int sum = 0; forward_list< int > myforwardlist{ 1, 5, 6, 3, 9, 2 }; while (!myforwardlist.empty()) { sum = sum + myforwardlist.front(); myforwardlist.pop_front(); } cout << sum; return 0; } |
输出
26
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END