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

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


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

Deque คืออะไร?

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

rend() คืออะไร?

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

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

ค่าที่คืน - คืนค่า reverse iterator ซึ่งชี้ไปยังตำแหน่งก่อนองค์ประกอบแรกของ deque

ตัวอย่าง

อินพุต Deque - 5 4 4 2 0

เอาต์พุต Reversed Deque - 0 2 4 4 5

อินพุต Deque - R E C T I F I E R

เอาต์พุต Reversed Deque - R E I F I T C E R

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

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

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

ตัวอย่าง

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

int main() {
    // initializing the deque
    deque<int> dq = { 7, 4, 0, 3, 7 };
    // 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: 7 4 0 3 7
Reversed Deque: 7 3 0 4 7

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

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

int main() {
    // initializing deque
    deque<char> dq = { 'S', 'U', 'B', 'T', 'R', 'A', '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: S U B T R A C T
Reversed deque: T C A R T B U S