ในบทความนี้เราจะอธิบาย set::max_size() ใน C++ STL รวมถึงไวยากรณ์ การทำงาน และค่าที่ส่งคืน
Set ใน C++ STL คืออะไร?
Set ใน C++ STL เป็นคอนเทนเนอร์ที่เก็บ องค์ประกอบที่ไม่ซ้ำกัน (unique) ในลำดับที่จัดเรียงแล้ว ค่าขององค์ประกอบระบุตัวตนของมันเอง เมื่อเพิ่มค่าใน set แล้วไม่สามารถแก้ไขได้ แต่ยังสามารถลบหรือเพิ่มค่าใหม่ได้ Set ถูกนำไปใช้งานเป็น binary search tree
set::max_size() คืออะไร?
max_size() เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <set> ฟังก์ชันนี้ส่งคืน ขนาดสูงสุด (maximum size) ของ set container ที่เกี่ยวข้อง นั่นคือขนาดสูงสุดที่ container สามารถบรรจุได้ อย่างไรก็ตาม ไม่รับประกันว่าจะจัดสรรหน่วยความจำได้จริงถึงขนาดนั้น อาจยังล้มเหลวในการจัดสรรที่จุด מסויםของ set container
ไวยากรณ์ (Syntax)
name_of_set.max_size();
พารามิเตอร์ (Parameters)
ฟังก์ชันนี้ไม่รับพารามิเตอร์ใดๆ
ค่าที่ส่งคืน (Return Value)
ส่งคืนขนาดสูงสุดของ set container ที่เกี่ยวข้อง
ตัวอย่างการใช้งาน
Input: set<int> myset; myset.max_size(); Output: size of a set before inserting elements: 461168601842738790 (ขึ้นอยู่กับระบบ)
ตัวอย่างโค้ดเต็ม 1
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> data_1, data_2;
data_1.insert(100);
cout << "size of a set after inserting values : " << data_1.max_size() << endl;
cout << "size of a set before inserting values : " << data_2.max_size();
return 0;
}
ผลลัพธ์ (Output)
size of a set after inserting values : 461168601842738790 size of a set before inserting values : 461168601842738790
ตัวอย่างโค้ดเต็ม 2
#include <iostream>
#include <set>
int main() {
int i;
std::set<int> Set;
if(Set.max_size() > 1000) {
for (i = 0; i <= 1000; i++)
Set.insert(i);
std::cout << "There are 1000 elements in a set.\n";
} else {
std::cout << "There can't be 1000 elements in a set.\n";
}
return 0;
}
ผลลัพธ์ (Output)
There are 1000 elements in a set.