งานนี้เป็นการแสดงฟังก์ชันการทำงานของ deque::push_back() ใน C++ STL
Deque คืออะไร
Deque หรือ Double Ended Queues เป็นคอนเทนเนอร์ลำดับที่ให้ฟังก์ชันการขยายและหดตัวได้ทั้งสองข้าง คิวโครงสร้างข้อมูลทั่วไปอนุญาตให้แทรกข้อมูลเฉพาะที่ท้ายและลบข้อมูลจากหน้าเท่านั้น การเปรียบเทียบกับคิวที่ป้ายรถเมล์ ที่คนสามารถแทรกเข้าคิวได้เฉพาะท้าย และคนหน้าสุดจะออกก่อน ส่วน deque แทรกและลบได้ทั้งสองข้าง
deque::push_back() คืออะไร
ฟังก์ชัน push_back() ใช้สำหรับแทรกองค์ประกอบใหม่เข้าไปใน deque ที่ท้าย
ไวยากรณ์
deque_name.push_back(value)
พารามิเตอร์
value - กำหนดองค์ประกอบใหม่ที่จะแทรกที่ท้ายของ deque
ตัวอย่าง
อินพุต Deque - 45 46 47 48 49
เอาต์พุต New Deque - 45 46 47 48 49 50
อินพุต Deque - B L A N K E T
เอาต์พุต New Deque - B L A N K E T S
แนวทางการทำงาน
- ประกาศ deque ก่อน
- พิมพ์ deque
- กำหนดฟังก์ชัน push_back()
ด้วยแนวทางด้านบน เราสามารถแทรกองค์ประกอบใหม่ที่ท้ายของ deque ได้ องค์ประกอบใหม่ควรมีชนิดข้อมูลเดียวกับ deque
ตัวอย่าง
// C++ code to demonstrate the working of deque push_back() function
#include <iostream>
#include <deque>
using namespace std;
int main() {
// initializing the deque
deque<int> dq = { 71, 75, 73, 76, 77 };
// print the deque
cout << "Deque: ";
for(auto x = dq.begin(); x != dq.end(); ++x)
cout << *x << " ";
// defining the push_back() function
dq.push_back(78);
// printing new deque after inserting new element
cout << "\nNew Deque: ";
for(auto x = dq.begin(); x != dq.end(); ++x)
cout << *x << " ";
return 0;
}เอาต์พุต
Deque: 71 75 73 76 77 New Deque: 71 75 73 76 77 78
ตัวอย่างที่ 2
// C++ code to demonstrate the working of deque push_back() function
#include <iostream>
#include <deque>
using namespace std;
int main() {
// initializing deque
deque<int> dq = { 64, 65, 66, 69, 68 };
cout << "Deque: ";
for(auto x = dq.begin(); x != dq.end(); ++x)
cout << *x << " ";
// defining the push_back() function
dq.push_back(67);
// printing new deque after inserting new element
cout << "\nNew Deque: ";
for(auto x = dq.begin(); x != dq.end(); ++x)
cout << *x << " ";
return 0;
}เอาต์พุต
Deque: 64 65 66 69 68 New Deque: 64 65 66 69 68 67