Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน multiset crbegin() และ crend() ใน C++ STL

ในบทความนี้ เราจะอภิปรายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน multiset::crbegin() และ multiset::crend() ใน 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::crbegin() คืออะไร?

ฟังก์ชัน multiset::crbegin() เป็นฟังก์ชันสำเร็จรูปใน C++ STL ซึ่งถูกกำหนดในไฟล์หัวข้อ crbegin() หมายถึง constant reverse begin function หมายถึงฟังก์ชันนี้ส่งคืน constant iterator ชี้ไปยังองค์ประกอบสุดท้ายของ multiset container ฟังก์ชันนี้เป็นเวอร์ชันย้อนกลับของ multiset::cbegin()

Constant iterator สามารถใช้เพื่อวนลูปผ่าน multiset container ได้เท่านั้น ไม่สามารถเปลี่ยนแปลง multiset container ได้

ไวยากรณ์

ms_name.crbegin();

พารามิเตอร์

ฟังก์ชันไม่ยอมรับพารามิเตอร์

ค่าที่ส่งคืน

ฟังก์ชันนี้ส่งคืน constant iterator ซึ่งชี้ไปยังองค์ประกอบสุดท้ายของ container

ตัวอย่าง

Input

std::multiset<int> mymultiset = {1, 2, 2, 3, 4}; mymultiset.crbegin();

Output

4

ตัวอย่าง

#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 crbegin() function: " << *(check.crbegin()) << endl;
    for(auto i = check.crbegin(); i != check.crend(); i++)
        cout << *i << " ";
    return 0;
}

ผลลัพธ์

First element fetched using crbegin() function: 60
60 50 40 30 20 10

multiset::crend() คืออะไร?

ฟังก์ชัน multiset::crend() เป็นฟังก์ชันสำเร็จรูปใน C++ STL ซึ่งถูกกำหนดในไฟล์หัวข้อ <set> crend() หมายถึง constant end function หมายถึงฟังก์ชันนี้ส่งคืน constant iterator ชี้ไปยังองค์ประกอบก่อนหน้าองค์ประกอบแรกของ multiset container นี่คือเวอร์ชันย้อนกลับของ cend()

Constant iterator สามารถใช้เพื่อวนลูปผ่าน multiset container ได้เท่านั้น ไม่สามารถเปลี่ยนแปลง multiset container ได้

ไวยากรณ์

ms_name.crend();

พารามิเตอร์

ฟังก์ชันไม่ยอมรับพารามิเตอร์

ค่าที่ส่งคืน

ฟังก์ชันนี้ส่งคืน constant iterator ซึ่งชี้ไปยังองค์ประกอบก่อนหน้าตัวแรกของ container

ตัวอย่าง

Input

std::multiset<int> mymultiset = {1, 2, 2, 3, 4}; mymultiset.crend();

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.crbegin(); i != check.crend(); i++)
        cout << *i << " ";
    return 0;
}

ผลลัพธ์

Elements in the list are: 60 50 40 30 20 10