ในบทความนี้ เราจะอภิปรายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน multiset::equal_range() ใน 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::equal_range() คืออะไร?
ฟังก์ชัน multiset::equal_range() เป็นฟังก์ชันสำเร็จรูปใน C++ STL ซึ่งถูกกำหนดในไฟล์หัวข้อ <set> equal_range() รับช่วงขององค์ประกอบที่เท่ากันใน multiset container
ฟังก์ชันนี้ส่งคืนขอบเขตของช่วงที่รวมองค์ประกอบทั้งหมดใน container ที่เท่ากับพารามิเตอร์ที่เราให้กับฟังก์ชัน
ไวยากรณ์
ms_name.equal_range(value_type& val);
พารามิเตอร์
ฟังก์ชันยอมรับพารามิเตอร์หนึ่ง:
- val - ค่าที่เรากำลังค้นหาช่วงใน container
ค่าที่ส่งคืน
ฟังก์ชันนี้ส่งคืนคู่ของ lower bound และ upper bound ซึ่งค่าของพวกเขาเท่ากับ
ตัวอย่าง
Input
std::multiset<int> mymultiset = {1, 2, 2, 3, 4}; mymultiset.equal_range(2);
Output
2 2
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int main() {
multiset<int> check;
check.insert(10);
check.insert(20);
check.insert(30);
check.insert(40);
check.insert(50);
check.insert(60);
check.insert(70);
check.insert(80);
cout << "Elements are: ";
for (auto i = check.begin(); i != check.end(); i++)
cout << *i << " ";
// lower bound และ upper bound
auto i = check.equal_range(30);
cout << "\nThe lower bound of 30 is " << *i.first;
cout << "\nThe upper bound of 30 is " << *i.second;
// องค์ประกอบสุดท้าย
i = check.equal_range(20);
cout << "\nThe lower bound of 20 is " << *i.first;
cout << "\nThe upper bound of 20 is " << *i.second;
i = check.equal_range(80);
cout << "\nThe lower bound of 80 is " << *i.first;
cout << "\nThe upper bound of 80 is " << *i.second;
return 0;
}
ผลลัพธ์
Elements are: 10 20 30 40 50 60 70 80 The lower bound of 30 is 30 The upper bound of 30 is 40 The lower bound of 20 is 20 The upper bound of 20 is 30 The lower bound of 80 is 80 The upper bound of 80 is 80