ในบทความนี้เราจะอธิบายฟังก์ชัน set::crbegin() และ set::crend() ใน C++ STL รวมถึงไวยากรณ์ การทำงาน และค่าที่ส่งคืน
Set ใน C++ STL คืออะไร?
Set ใน C++ STL เป็นคอนเทนเนอร์ที่เก็บ องค์ประกอบที่ไม่ซ้ำกัน (unique) ในลำดับที่จัดเรียงแล้ว ค่าขององค์ประกอบระบุตัวตนของมันเอง เมื่อเพิ่มค่าใน set แล้วไม่สามารถแก้ไขได้ แต่ยังสามารถลบหรือเพิ่มค่าใหม่ได้ Set ถูกนำไปใช้งานเป็น binary search tree
set::crbegin() คืออะไร?
crbegin() ย่อมาจาก constant reverse begin iterator เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <set> ฟังก์ชันนี้ส่งคืน iterator ที่ชี้ไปยัง องค์ประกอบตัวสุดท้าย ของ set container (เหมือน rbegin() แต่เป็น constant iterator) เนื่องจาก iterator ทั้งหมดใน set เป็น constant iterator จึงไม่สามารถใช้แก้ไขเนื้อหาได้ ใช้ได้แค่วนลูปเท่านั้น
ไวยากรณ์ (Syntax)
constant_iterator name_of_set.crbegin();
พารามิเตอร์ (Parameters)
ฟังก์ชันนี้ไม่รับพารามิเตอร์ใดๆ
ค่าที่ส่งคืน (Return Value)
ส่งคืน iterator ที่ชี้ไปยังองค์ประกอบตัวสุดท้ายของ set container
ตัวอย่างการใช้งาน
Input: set<int> myset = {1, 2, 3, 4, 5};
myset.crbegin();
Output: 5
ตัวอย่างโค้ดเต็ม
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5};
set<int> ch(arr, arr + 5);
for (auto i = ch.crbegin(); i != ch.crend(); i++)
cout << *i << " ";
return 0;
}
ผลลัพธ์ (Output)
5 4 3 2 1
set::crend() คืออะไร?
crend() ย่อมาจาก constant reverse end iterator เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <set> ฟังก์ชันนี้ส่งคืน iterator ที่ชี้ไปยัง ตำแหน่งก่อนองค์ประกอบตัวแรก ของ set container (เหมือน rend() แต่เป็น constant iterator) ใช้สำหรับวนลูปแบบย้อนหลังร่วมกับ crbegin()
ไวยากรณ์ (Syntax)
constant_iterator name_of_set.crend();
พารามิเตอร์ (Parameters)
ฟังก์ชันนี้ไม่รับพารามิเตอร์ใดๆ
ค่าที่ส่งคืน (Return Value)
ส่งคืน iterator ที่ชี้ไปยังตำแหน่งก่อนองค์ประกอบตัวแรกของ set container
ตัวอย่างการใช้งาน
Input: set<int> myset = {1, 2, 3, 4, 5};
myset.crend();
Output: Iterator ชี้ตำแหน่งก่อน 1 (ค่าสุ่ม/ไม่กำหนด)
ตัวอย่างโค้ดเต็ม
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {3, 5, 8, 1, 9};
set<int> ch(arr, arr + 5);
for(auto i = ch.crbegin(); i != ch.crend(); i++)
cout << *i << " ";
return 0;
}
ผลลัพธ์ (Output)
9 8 5 3 1