ในบทความนี้ เราจะอภิปรายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน multiset::cbegin() และ multiset::cend() ใน C++ STL
Multiset ใน C++ STL คืออะไร?
Multisets เป็น containers ที่คล้ายกับ set container หมายถึงพวกมันเก็บค่าในรูปแบบของ keys เหมือนกับ set ในลำดับเฉพาะ
ใน multiset ค่าถูกระบุเป็น keys เหมือนกับ sets ความแตกต่างหลักระหว่าง multiset และ set คือ set มี keys ที่แตกต่างกัน หมายถึงไม่มี keys สองตัวเหมือนกัน ใน multiset อาจมีค่า keys เดียวกันได้
Multiset keys ถูกใช้เพื่อ implement binary search trees
multiset::cbegin() คืออะไร?
ฟังก์ชัน multiset::cbegin() เป็นฟังก์ชันสำเร็จรูปใน C++ STL ซึ่งถูกกำหนดในไฟล์หัวข้อ <set> cbegin() หมายถึง constant begin function หมายถึงฟังก์ชันนี้ส่งคืน constant iterator ชี้ไปยังจุดเริ่มต้นของ multiset container
Constant iterator สามารถใช้เพื่อวนลูปผ่าน multiset container ได้เท่านั้น ไม่สามารถเปลี่ยนแปลง multiset container ได้
ไวยากรณ์
ms_name.cbegin();
พารามิเตอร์
ฟังก์ชันไม่ยอมรับพารามิเตอร์
ค่าที่ส่งคืน
ฟังก์ชันนี้ส่งคืน constant iterator ซึ่งชี้ไปยังองค์ประกอบแรกของ container
ตัวอย่าง
Input
std::multiset<int> mymultiset = {1, 2, 2, 3, 4}; mymultiset.cbegin();
Output
1
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50, 60};
multiset<int> check(arr, arr + 6);
cout << "First element fetched using cbegin() function: " << *(check.cbegin()) << endl;
for(auto i = check.cbegin(); i != check.cend(); i++)
cout << *i << " ";
return 0;
}
ผลลัพธ์
First element fetched using cbegin() function: 10 10 20 30 40 50 60
multiset::cend() คืออะไร?
ฟังก์ชัน multiset::cend() เป็นฟังก์ชันสำเร็จรูปใน C++ STL ซึ่งถูกกำหนดในไฟล์หัวข้อ <set> cend() หมายถึง constant end function หมายถึงฟังก์ชันนี้ส่งคืน constant iterator ชี้ไปยังตำแหน่งหลังองค์ประกอบสุดท้ายของ multiset container
Constant iterator สามารถใช้เพื่อวนลูปผ่าน multiset container ได้เท่านั้น ไม่สามารถเปลี่ยนแปลง multiset container ได้
ไวยากรณ์
ms_name.cend();
พารามิเตอร์
ฟังก์ชันไม่ยอมรับพารามิเตอร์
ค่าที่ส่งคืน
ฟังก์ชันนี้ส่งคืน constant iterator ซึ่งชี้ไปยังองค์ประกอบหลังตัวสุดท้ายของ container
ตัวอย่าง
Input
std::multiset<int> mymultiset = {1, 2, 2, 3, 4}; mymultiset.cend();
Output
error
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50, 60};
multiset<int> check(arr, arr + 6);
cout << "Elements in the list are: ";
for(auto i = check.cbegin(); i != check.cend(); i++)
cout << *i << " ";
return 0;
}
ผลลัพธ์
Elements in the list are: 10 20 30 40 50 60