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

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

ภาพรวม

deque::crbegin() เป็น Member Function ของ std::deque (header <deque>) คืนค่า Const Reverse Iterator ชี้ไปยัง องค์ประกอบสุดท้าย ของ Deque (Reverse Beginning)

Syntax

const_reverse_iterator crbegin() const noexcept;

คุณสมบัติ

  • crbegin = Constant Reverse Begin
  • คืนค่า const_reverse_iterator - Iterator แบบย้อนกลับที่อ่านอย่างเดียว
  • ชี้ไปยังองค์ประกอบสุดท้าย (index = size()-1)
  • การ ++iterator จะเคลื่อนไปทางซ้าย (มุ่งหน้าตัวแรก)
  • เวอร์ชัน Non-const คือ rbegin()

ตัวอย่างโค้ด

#include <iostream>
#include <deque>
using namespace std;

int main() {
    deque<int> mydeque = {1, 2, 3, 4, 5};

    cout << "mydeque backwards: ";
    for (auto rit = mydeque.crbegin(); rit != mydeque.crend(); ++rit)
        cout << ' ' << *rit;
    cout << '\n';

    // ใช้กับ Range-based for (C++11)
    cout << "Using range-based: ";
    for (const auto& x : mydeque)  // หมายเหตุ: range-based ใช้ begin/end ไม่ใช่ rbegin/rend
        cout << x << " ";
    cout << endl;

    return 0;
}

ผลลัพธ์

mydeque backwards: 5 4 3 2 1

คำอธิบายเพิ่มเติม

  • Const Reverse Iterator ใช้สำหรับ อ่านค่าจากหลังมาหน้า โดยไม่สามารถแก้ไขได้
  • คู่คือ crend() (ชี้ก่อนองค์ประกอบแรก)
  • เหมาะสำหรับอัลกอริทึมที่ต้องการ Process แบบย้อนกลับ เช่น Palindrome Check, Reverse Search
  • Deque รองรับ Random Access Iterator ทำให้ crbegin()/crend() ทำงานได้อย่างมีประสิทธิภาพ

การใช้งานร่วมกับ Algorithms

#include <algorithm>
#include <deque>
#include <iostream>
using namespace std;

int main() {
    deque<int> d = {1, 2, 3, 4, 5};

    // หาค่าแรกจากท้ายที่มากกว่า 3
    auto it = find_if(d.crbegin(), d.crend(), [](int x){ return x > 3; });
    if (it != d.crend())
        cout << "Found from back: " << *it << endl;  // 5

    // Copy แบบย้อนกลับ
    vector<int> v;
    copy(d.crbegin(), d.crend(), back_inserter(v));
    // v = {5, 4, 3, 2, 1}
    return 0;
}

ฟังก์ชัน Iterator คู่ของ Deque (สรุป)

ทิศทางMutableConst
Forwardbegin() / end()cbegin() / cend()
Reverserbegin() / rend()crbegin() / crend()