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

deque::begin() และ deque::end() ใน C++ STL


ในบทความนี้เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน deque::begin() และ deque::end() ใน C++ Standard Template Library (STL)

Deque คืออะไร?

Deque (Double Ended Queue) เป็นคอนเทนเนอร์ลำดับที่ให้ฟังก์ชันการขยายและหดตัวได้ที่ทั้งสองปลาย โครงสร้าง queue ทั่วไปอนุญาตให้แทรกข้อมูลเฉพาะที่ปลาย (END) และลบข้อมูลจากหน้า (FRONT) เท่านั้น ส่วน Deque อนุญาตให้แทรกและลบข้อมูลได้ที่ทั้งสองปลาย

deque::begin() คืออะไร?

deque::begin() เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <deque> ฟังก์ชันนี้ส่งคืน iterator ที่อ้างอิงถึง องค์ประกอบตัวแรก ของ deque container ทั้ง begin() และ end() ใช้สำหรับวนลูปผ่าน deque container

ไวยากรณ์ (Syntax)

mydeque.begin();

พารามิเตอร์ (Parameters)

ฟังก์ชันนี้ไม่รับพารามิเตอร์ใดๆ

ค่าที่ส่งคืน (Return Value)

ส่งคืน iterator ที่ชี้ไปยังองค์ประกอบตัวแรกใน deque container

ตัวอย่างการใช้งาน

Input: deque<int> mydeque = {10, 20, 30, 40};
mydeque.begin();
Output: Element at the beginning is = 10

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

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

int main() {
    deque<int> Deque = {2, 4, 6, 8, 10 };
    cout << "Elements are : ";
    for (auto i = Deque.begin(); i != Deque.end(); ++i)
        cout << ' ' << *i;
    return 0;
}

ผลลัพธ์ (Output)

Elements are : 2 4 6 8 10

deque::end() คืออะไร?

deque::end() เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <deque> ฟังก์ชันนี้ส่งคืน iterator ที่อ้างอิงถึง ตำแหน่งถัดจากองค์ประกอบตัวสุดท้าย (one past the end) ของ deque container ทั้ง begin() และ end() ใช้สำหรับวนลูปผ่าน deque container

ไวยากรณ์ (Syntax)

mydeque.end();

พารามิเตอร์ (Parameters)

ฟังก์ชันนี้ไม่รับพารามิเตอร์ใดๆ

ค่าที่ส่งคืน (Return Value)

ส่งคืน iterator ที่ชี้ไปยังตำแหน่งถัดจากองค์ประกอบตัวสุดท้ายใน deque container

ตัวอย่างการใช้งาน

Input: deque<int> mydeque = {10, 20, 30, 40};
mydeque.end();
Output: Iterator ชี้ตำแหน่งหลัง 40 (ค่าสุ่ม/ไม่กำหนด)

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

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

int main() {
    deque<int> Deque = { 10, 20, 30, 40};
    cout << "Elements are : ";
    for (auto i = Deque.begin(); i != Deque.end(); ++i)
        cout << ' ' << *i;
    return 0;
}

ผลลัพธ์ (Output)

Elements are : 10 20 30 40