งานนี้เป็นการแสดงฟังก์ชันการทำงานของ deque::insert() ใน C++ STL
Deque คืออะไร?
Deque หรือ Double Ended Queues เป็นคอนเทนเนอร์ลำดับที่ให้ฟังก์ชันการขยายและหดตัวได้ทั้งสองข้าง คิวโครงสร้างข้อมูลทั่วไปอนุญาตให้แทรกข้อมูลเฉพาะที่ท้ายและลบข้อมูลจากหน้าเท่านั้น การเปรียบเทียบกับคิวที่ป้ายรถเมล์ ที่คนสามารถแทรกเข้าคิวได้เฉพาะท้าย และคนหน้าสุดจะออกก่อน ส่วน deque แทรกและลบได้ทั้งสองข้าง
insert() คืออะไร?
ฟังก์ชัน deque::insert() ใช้สำหรับแทรกองค์ประกอบใน deque
- ใช้แทรกองค์ประกอบที่ตำแหน่งที่ระบุ
- ใช้แทรก n องค์ประกอบใน deque
- ใช้แทรกช่วงขององค์ประกอบที่ตำแหน่งที่ระบุ
ไวยากรณ์
deque_name.insert(iterator position, const value_type& value) deque_name.insert(iterator position, size_type n, const value_type& value) deque_name.insert(iterator position, iterator first, iterator last)
พารามิเตอร์
- Value - ระบุองค์ประกอบใหม่ที่จะแทรก
- n - ระบุจำนวนองค์ประกอบที่จะแทรก
- first, last - ระบุ iterator ที่กำหนดช่วงขององค์ประกอบที่จะแทรก
ค่าที่คืน
คืนค่า iterator ที่ชี้ไปยังองค์ประกอบแรกที่แทรกใหม่
ตัวอย่าง
อินพุต Deque - 1 2 3 4 5
เอาต์พุต New Deque - 1 1 2 3 4 5
อินพุต Deque - 11 12 13 14 15
เอาต์พุต New Deque - 11 12 12 12 13 14 15
แนวทางการทำงาน
- ประกาศ deque ก่อน
- พิมพ์ deque
- ประกาศฟังก์ชัน insert()
ด้วยแนวทางด้านบน เราสามารถแทรกองค์ประกอบใหม่ได้
ตัวอย่าง
// C++ code to demonstrate the working of deque insert() function
#include <iostream>
#include <deque>
using namespace std;
int main() {
// declaring the deque
deque<int> dq = { 55, 84, 38, 66, 67 };
// print the deque
cout << "Deque: ";
for(auto x = dq.begin(); x != dq.end(); ++x)
cout << *x << " ";
// declaring insert() function
auto it = dq.insert(dq.begin(), 22);
// printing deque after inserting new element
cout << "\nNew Deque: ";
for(auto x = dq.begin(); x != dq.end(); ++x)
cout << *x << " ";
return 0;
}เอาต์พุต
Deque: 55 84 38 66 67 New Deque: 22 55 84 38 66 67
ตัวอย่างที่ 2
// C++ code to demonstrate the working of deque insert() function
#include <iostream>
#include <deque>
using namespace std;
int main() {
deque<char> dq = { 'B', 'L', 'D' };
cout << "Deque: ";
for(auto x = dq.begin(); x != dq.end(); ++x)
cout << *x << " ";
dq.insert(dq.begin() + 1, 2, 'O');
// printing deque after inserting new element
cout << "\nNew Deque: ";
for(auto x = dq.begin(); x != dq.end(); ++x)
cout << *x << " ";
return 0;
}เอาต์พุต
Deque: B L D New Deque: B O O L D
ตัวอย่างที่ 3
// C++ code to demonstrate the working of deque insert() function
#include <iostream>
#include <deque>
#include <vector>
using namespace std;
int main() {
deque<int> dq = { 65, 54, 32, 98, 55 };
cout << "Deque: ";
for(auto x = dq.begin(); x != dq.end(); ++x)
cout << *x << " ";
vector<int> v(3, 19);
dq.insert(dq.begin(), v.begin(), v.end());
// printing deque after inserting new element
cout << "\nNew Deque: ";
for(auto x = dq.begin(); x != dq.end(); ++x)
cout << *x << " ";
return 0;
}เอาต์พุต
Deque: 65 54 32 98 55 New Deque: 19 19 19 65 54 32 98 55