ในบทความนี้ เราจะพูดถึง set::max_size() ใน C++ STL, ไวยากรณ์, การทำงาน และค่าที่ส่งคืน
การตั้งค่าใน C++ STL คืออะไร
ชุดใน C++ STL คือคอนเทนเนอร์ที่ต้องมีองค์ประกอบที่ไม่ซ้ำกันในลำดับทั่วไป ชุดต้องมีองค์ประกอบที่ไม่ซ้ำกันเนื่องจากค่าขององค์ประกอบระบุองค์ประกอบ เมื่อเพิ่มค่าในคอนเทนเนอร์ชุดแล้วจะแก้ไขในภายหลังไม่ได้ แม้ว่าเราจะยังสามารถลบหรือเพิ่มค่าลงในชุดได้ ชุดถูกใช้เป็นแผนผังการค้นหาแบบไบนารี
ชุดอะไร::max_size()?
max_size() เป็นฟังก์ชัน inbuilt ใน C++ STL ซึ่งประกาศไว้ในไฟล์ส่วนหัว
ไวยากรณ์
name_of_set.max_size();
พารามิเตอร์
ฟังก์ชันนี้ไม่รับพารามิเตอร์ใดๆ
คืนค่า
ฟังก์ชันนี้จะคืนค่าขนาดสูงสุดของคอนเทนเนอร์ชุดที่เกี่ยวข้อง
ตัวอย่าง
Input: set<int> myset; myset.max_size(); Output: size of a set before inserting elements: 461168601842738790
ตัวอย่าง
#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;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น มันจะสร้างผลลัพธ์ต่อไปนี้ -
size of a set after inserting values : 461168601842738790 size of a set before inserting values : 461168601842738790
ตัวอย่าง
#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;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น มันจะสร้างผลลัพธ์ต่อไปนี้ -
There are 1000 elements in a set.