ในบทความนี้เราจะอธิบายฟังก์ชัน set::cbegin() และ set::cend() ใน C++ STL รวมถึงไวยากรณ์ การทำงาน และค่าที่ส่งคืน
Set ใน C++ STL คืออะไร?
Set ใน C++ STL เป็นคอนเทนเนอร์ที่เก็บ องค์ประกอบที่ไม่ซ้ำกัน (unique) ในลำดับที่จัดเรียงแล้ว ค่าขององค์ประกอบระบุตัวตนของมันเอง เมื่อเพิ่มค่าใน set แล้วไม่สามารถแก้ไขได้ แต่ยังสามารถลบหรือเพิ่มค่าใหม่ได้ Set ถูกนำไปใช้งานเป็น binary search tree
set::cbegin() คืออะไร?
cbegin() ย่อมาจาก constant begin iterator เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <set> ฟังก์ชันนี้ส่งคืน constant iterator ที่ชี้ไปยัง องค์ประกอบตัวแรก ใน set container เนื่องจาก iterator ทั้งหมดใน set เป็น constant iterator จึงไม่สามารถใช้แก้ไขเนื้อหาได้ ใช้ได้แค่วนลูปผ่านองค์ประกอบ
ไวยากรณ์ (Syntax)
constant_iterator name_of_set.cbegin();
พารามิเตอร์ (Parameters)
ฟังก์ชันนี้ไม่รับพารามิเตอร์ใดๆ
ค่าที่ส่งคืน (Return Value)
ส่งคืน constant_iterator ที่ชี้ไปยังองค์ประกอบตัวแรก
ตัวอย่างการใช้งาน
Input: set<int> set_a = {18, 34, 12, 10, 44};
set_a.cbegin();
Output: Beginning element in the set container: 10
ตัวอย่างโค้ดเต็ม 1
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> set_a = {18, 34, 12, 10, 44};
cout << "Beginning element in the set container: ";
cout << *(set_a.cbegin());
return 0;
}
ผลลัพธ์ (Output)
Beginning element in the set container: 10
ตัวอย่างโค้ดเต็ม 2: วนลูปด้วย cbegin/cend
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> set_a = {18, 34, 12, 10, 44};
cout << "set_a contains:";
for (auto it = set_a.cbegin(); it != set_a.cend(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
}
ผลลัพธ์ (Output)
set_a contains: 10 12 18 34 44
set::cend() คืออะไร?
cend() ย่อมาจาก constant end iterator เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <set> ฟังก์ชันนี้ส่งคืน constant iterator ขององค์ประกอบที่ ตำแหน่งถัดจากองค์ประกอบตัวสุดท้าย (past-the-end) ใน set container ใช้ร่วมกับ cbegin() หรือ begin() เพื่อวนลูปผ่าน set ทั้งหมด
ไวยากรณ์ (Syntax)
constant_iterator name_of_set.cend();
พารามิเตอร์ (Parameters)
ฟังก์ชันนี้ไม่รับพารามิเตอร์ใดๆ
ค่าที่ส่งคืน (Return Value)
ส่งคืน constant_iterator ที่ชี้ไปยังตำแหน่ง past-the-end
ตัวอย่างการใช้งาน
Input: set<int> set_a = {18, 34, 12, 10, 44};
set_a.cend();
Output: Past to end element: (ค่าสุ่ม/ไม่กำหนด)
ตัวอย่างโค้ดเต็ม 3
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> set_a = {18, 34, 11, 10, 44};
cout << "Past to end element: ";
cout << *(set_a.cend()); // ค่าจะเป็นค่าสุ่ม (undefined behavior)
return 0;
}
ผลลัพธ์ (Output)
Past to end element: 5 We will get a random value
ตัวอย่างโค้ดเต็ม 4: วนลูปปกติ
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> set_a = {18, 34, 12, 10, 44};
cout << " set_a contains:";
for (auto it = set_a.cbegin(); it != set_a.cend(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
}
ผลลัพธ์ (Output)
set_a contains: 10 12 18 34 44