當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ list::begin()、list::end()用法及代碼示例


清單是C++中用於以非連續方式存儲數據的容器,通常,數組和向量本質上是連續的,因此,與列表中的插入和刪除選項相比,插入和刪除操作的成本更高。

list::begin()

begin()函數用於返回指向列表容器的第一個元素的迭代器。它與front()函數不同,因為front函數返回對容器第一個元素的引用,但begin()函數將雙向迭代器返回到容器的第一個元素。

用法:


listname.begin()
參數:
No parameters are passed.
返回:
This function returns a bidirectional
iterator pointing to the first element.

例子:

Input :mylist{1, 2, 3, 4, 5};
         mylist.begin();
Output:returns an iterator to the element 1

Input :mylist{8, 7};
         mylist.begin();
Output:returns an iterator to the element 8

錯誤和異常

1.它沒有異常拋出保證。
2.傳遞參數時顯示錯誤。

// CPP program to illustrate 
// Implementation of begin() function 
#include <iostream> 
#include <list> 
using namespace std; 
  
int main() 
{ 
    // declaration of list container 
    list<int> mylist{ 1, 2, 3, 4, 5 }; 
  
    // using begin() to print list 
    for (auto it = mylist.begin(); it != mylist.end(); ++it) 
        cout << ' ' << *it; 
    return 0; 
}

輸出:

1 2 3 4 5

時間複雜度:O(1)

list::end()

end()函數用於返回指向列表容器的最後一個元素的迭代器。它與back()函數不同,因為back()函數返回對容器最後一個元素的引用,但end()函數將雙向迭代器返回到容器的最後一個元素。

用法:

listname.end()
參數:
No parameters are passed.
返回:
This function returns a bidirectional
iterator pointing to the last element.

例子:

Input :mylist{1, 2, 3, 4, 5};
         mylist.end();
Output:returns an iterator to the element 5

Input :mylist{8, 7};
         mylist.end();
Output:returns an iterator to the element 7

錯誤和異常

1.它沒有異常拋出保證。
2.傳遞參數時顯示錯誤。

// CPP program to illustrate 
// Implementation of end() function 
#include <iostream> 
#include <list> 
using namespace std; 
  
int main() 
{ 
    // declaration of list container 
    list<int> mylist{ 1, 2, 3, 4, 5 }; 
  
    // using end() to print list 
    for (auto it = mylist.begin(); it != mylist.end(); ++it) 
        cout << ' ' << *it; 
    return 0; 
}

輸出:

1 2 3 4 5

時間複雜度:O(1)



相關用法


注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 list::begin() and list::end() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。