Trong bài viết này, chúng ta sẽ thảo luận về hoạt động, cú pháp và ví dụ của hàm list::end() trong C++.
list::end() là gì?
list::end() là hàm tích hợp trong C++ STL khai báo trong <list>. Hàm trả về iterator trỏ đến vị trí sau phần tử cuối cùng của list container. Hàm này không trỏ đến bất kỳ phần tử nào trong container.
Hàm này thường dùng kết hợp với list::begin() để xác định phạm vi của một list container cụ thể.
Cú pháp
list_container.end();
Hàm không nhận tham số.
Giá trị trả về
Trả về iterator quá cuối (past-the-end) của list container.
Ví dụ 1
Duyệt các phần tử trong list dùng end().
#include <bits/stdc++.h>
using namespace std;
int main() {
list<int> myList;
myList.push_back(67);
myList.push_back(12);
myList.push_back(32);
myList.push_back(780);
myList.push_back(78);
cout << "elements in the list are:\n";
for (auto it = myList.begin(); it != myList.end(); ++it) cout << *it << " ";
return 0;
}
Đầu ra
elements in the list are: 67 12 32 780 78
Ví dụ 2
Dùng header <list> truy cập phần tử qua iterator từ end().
#include <iostream>
#include <list>
int main() {
int values[] = {67, 12, 32, 780, 78};
std::list<int> myList(values, values+5);
std::cout << "elements in the list are:\n";
for (std::list<int>::iterator it = myList.begin(); it != myList.end(); ++it)
std::cout << ' ' << *it;
return 0;
}
Đầu ra
elements in the list are: 67 12 32 780 78