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

ฟังก์ชัน deque::rbegin() ใน C++ STL


งานนี้เป็นการแสดงฟังก์ชันการทำงานของ deque::rbegin() ใน C++ STL

Deque คืออะไร?

Deque หรือ Double Ended Queues เป็นคอนเทนเนอร์ลำดับที่ให้ฟังก์ชันการขยายและหดตัวได้ทั้งสองข้าง คิวโครงสร้างข้อมูลทั่วไปอนุญาตให้แทรกข้อมูลเฉพาะที่ท้ายและลบข้อมูลจากหน้าเท่านั้น การเปรียบเทียบกับคิวที่ป้ายรถเมล์ ที่คนสามารถแทรกเข้าคิวได้เฉพาะท้าย และคนหน้าสุดจะออกก่อน ส่วน deque แทรกและลบได้ทั้งสองข้าง

rbegin() คืออะไร?

ฟังก์ชัน rbegin() คืนค่า reverse iterator ที่ชี้ไปยังองค์ประกอบสุดท้ายใน deque ฟังก์ชัน rbegin() ทำให้ deque กลับด้าน

ไวยากรณ์ - deque_name.rbegin()

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

ตัวอย่าง

อินพุต Deque - 10 9 8 7 6 5 4 3 2 1

เอาต์พุต Reversed Deque - 1 2 3 4 5 6 7 8 9 10

อินพุต Deque - G O L D E N

เอาต์พุต Reversed Deque - N E D L O G

แนวทางการทำงาน

  • ประกาศ deque ก่อน
  • พิมพ์ deque
  • ใช้ฟังก์ชัน rbegin()
  • พิมพ์ deque ใหม่หลังการกลับด้าน

ด้วยแนวทางด้านบน เราสามารถได้ deque ที่กลับด้าน

ตัวอย่าง

// C++ code to demonstrate the working of deque rbegin() function
#include <iostream>
#include <deque>
using namespace std;

int main() {
    // initializing the deque
    deque<int> dq = { 5, 4, 0, 8, 5 };
    // print the deque
    cout << "Deque: ";
    for(auto x = dq.begin(); x != dq.end(); ++x)
        cout << *x << " ";
    // printing reverse deque
    cout << "\nReversed deque: ";
    for(auto x = dq.rbegin(); x != dq.rend(); ++x)
        cout << *x << " ";
    return 0;
}

เอาต์พุต

Deque: 5 4 0 8 5
Reversed Deque: 5 8 0 4 5

ตัวอย่างที่ 2

// C++ code to demonstrate the working of deque rbegin() function
#include <iostream>
#include <deque>
using namespace std;

int main() {
    // initializing deque
    deque<char> dq = { 'P', 'R', 'O', 'D', 'U', 'C', 'T' };
    cout << "Deque: ";
    for(auto x = dq.begin(); x != dq.end(); ++x)
        cout << *x << " ";
    // printing reversed deque
    cout << "\nReversed deque: ";
    for(auto x = dq.rbegin(); x != dq.rend(); ++x)
        cout << *x << " ";
    return 0;
}

เอาต์พุต

Deque: P R O D U C T
Reversed deque: T C U D O R P