STL中的轉發列表實現單鏈接列表。從C++ 11引入的前向列表在插入,刪除和移動操作(如排序)方麵比其他容器有用,並且允許時間常數插入和刪除元素。它與列表的不同之處在於前向列表會跟蹤對象的位置僅list的下一個元素同時跟蹤下一個和上一個元素。
forward_list::begin()
begin()函數用於返回指向向前列表容器的第一個元素的迭代器。 begin()函數將雙向迭代器返回到容器的第一個元素。
用法:
forwardlistname.begin()
參數:
No parameters are passed.
返回:
This function returns a bidirectional
iterator pointing to the first element.
例子:
Input :myflist{1, 2, 3, 4, 5}; myflist.begin(); Output:returns an iterator to the element 1 Input :myflist{8, 7}; myflist.begin(); Output:returns an iterator to the element 8
錯誤和異常
1.它沒有異常拋出保證。
2.傳遞參數時顯示錯誤。
// CPP program to illustrate
// Implementation of begin() function
#include <forward_list>
#include <iostream>
using namespace std;
int main()
{
// declaration of forward list container
forward_list<int> myflist{ 1, 2, 3, 4, 5 };
// using begin() to print list
for (auto it = myflist.begin(); it != myflist.end(); ++it)
cout << ' ' << *it;
return 0;
}
輸出:
1 2 3 4 5
時間複雜度:O(1)
forward_list::end()
end()函數用於返回指向列表容器的最後一個元素的迭代器。 end()函數將雙向迭代器返回到容器的最後一個元素。
用法:
forwardlistname.end() 參數: No parameters are passed. 返回: This function returns a bidirectional iterator pointing to the last element.
例子:
Input :myflist{1, 2, 3, 4, 5}; myflist.end(); Output:returns an iterator to the element 5 Input :myflist{8, 7}; myflist.end(); Output:returns an iterator to the element 7
錯誤和異常
1.它沒有異常拋出保證。
2.傳遞參數時顯示錯誤。
// CPP program to illustrate
// Implementation of end() function
#include <forward_list>
#include <iostream>
using namespace std;
int main()
{
// declaration of forward list container
forward_list<int> myflist{ 1, 2, 3, 4, 5 };
// using end() to print forward list
for (auto it = myflist.begin(); it != myflist.end(); ++it)
cout << ' ' << *it;
return 0;
}
輸出:
1 2 3 4 5
時間複雜度:O(1)
相關用法
注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 forward_list::begin() and forward_list::end() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。