Contents
- forward_list được implement giống danh sách liên kết đơn (Single Link List).
- forward_list cho phép chèn, xóa nhanh các phần tử trong container.
- forward_list không support Fast Random Access.
Cú pháp
std::forward_list<data_type> name_object;
data_type: kiểu dữ liệu
name_object: tên đối tượng
Function
Function | Ý nghĩa |
front() | Trả về phần tử đầu của forward_list |
push_front() | Chèn phần tử vào đầu danh sách |
pop_front() | Remove phần tử đầu danh sách |
insert_after() | Chèn phần tử sau một phần tử khác |
erase_after() | Xóa phần tử trong danh sách |
clear() | Xóa nội dung danh sách |
empty() | Trả về true, nếu danh sách rỗng.
Trả về false, nếu danh sách có ít nhất 1 phần tử. |
max_size() | Trả về số lượng phần tử mà danh sách có khả năng lưu trữ được. |
resize() | Thay đổi kích thước của danh sách |
swap() | Swap nội dung giữa 2 list |
Ví dụ: Minh họa các fuction của foward_list
#include <forward_list> #include <string> #include <iostream> #include <vector> using namespace std; void printfwlist(forward_list<std::string> words); int main() { std::forward_list<std::string> words; std::forward_list<std::string>::iterator i; /* push_front() */ words.push_front("Developer"); words.push_front("a"); words.push_front("I'm"); cout << "forward_list: "; printfwlist(words); cout << "max_size() : " << words.max_size() << endl; /* front() */ words.front() = "He's"; cout << "\nfront(): "; printfwlist(words); /* pop_front() */ words.pop_front(); cout << "\npop_front(): "; printfwlist(words); /* insert_after() */ i = words.begin(); words.insert_after(i, "Senior"); cout << "\ninsert_after(i, \"Senior\"): "; printfwlist(words); /* erase_after() */ i = words.begin(); words.erase_after(i); cout << "\nerase_after(i): "; printfwlist(words); /* resize() */ words.resize(5, "XX"); cout << "\nresize(i): "; printfwlist(words); system("pause"); return 0; } void printfwlist(forward_list<std::string> words) { forward_list<std::string>::iterator i; for (i = words.begin(); i != words.end(); i++) { cout << *i << " "; } cout << endl; }
Kết quả:
Leave a Reply
You must be logged in to post a comment.