ฟังก์ชัน list::size() ใน C++ STL
List ใน STL
Doubly-linked list รองรับ insertion/deletion แบบ constant time ใดๆ จองหน่วยความจำไม่ต่อเนื่อง
list::size()
คืนจำนวนองค์ประกอบใน list container
Syntax
list_container.size()
พารามิเตอร์
ไม่มี
คืนค่า
size_type (โดยปกติคือ size_t) จำนวนองค์ประกอบ
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int main() {
list<int> myList;
myList.push_back(23);
myList.push_back(12);
myList.push_back(21);
int size = myList.size();
cout << "size of the list is: " << size;
return 0;
}
Output: size of the list is: 3
ข้อสังเกตเกี่ยวกับประสิทธิภาพ
- C++11 ขึ้นไป:
size()เป็น O(1) (เก็บ size ไว้ใน container) - C++98/03: อาจเป็น O(n) (ต้องนับทุกครั้ง) ขึ้นกับ implementation
- ใช้
empty()แทนsize() == 0เพื่อความชัดเจนและประสิทธิภาพ
ฟังก์ชันที่เกี่ยวข้อง
empty()- true ถ้าว่างmax_size()- ขนาดสูงสุดทฤษฎีresize(n)- ปรับขนาด