C++ STL 中的 deque_insert()
本任務旨在展示 C++ STL 中 Deque insert() 函式的功能。
什麼是 Deque?
Deque 是雙端佇列,是一種序列容器,可以在兩端進行擴充套件和收縮操作。佇列資料結構只允許使用者在隊尾插入資料,在隊首刪除資料。打個比方,就像公交車站的隊伍,只能在隊尾排隊,而排在隊首的人先下車。但在雙端佇列中,可以在兩端進行資料的插入和刪除。
什麼是 insert()?
deque insert() 函式用於在 deque 中插入元素。
該函式用於在指定位置插入元素。
該函式還用於在 deque 中插入 n 個元素。
它還用於在指定位置插入指定範圍內的元素。
語法
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 – 指定迭代器,用於指定要插入的元素範圍。
返回值
它返回一個指向第一個新插入元素的迭代器。
示例
輸入 Deque − 1 2 3 4 5
輸出 新的 Deque − 1 1 2 3 4 5
輸入 Deque − 11 12 13 14 15
輸出 新的 Deque − 11 12 12 12 13 14 15
可遵循的方法
首先宣告 deque。
然後列印 deque。
然後宣告 insert() 函式。
使用上述方法,可以插入新元素。
示例
// C++ code to demonstrate the working of deque insert( ) function #include<iostream.h> #include<deque.h> Using namespace std; int main ( ){ // declaring the deque Deque<int> deque = { 55, 84, 38, 66, 67 }; // print the deque cout<< “ Deque: “; for( auto x = deque.begin( ); x != deque.end( ); ++x) cout<< *x << “ “; // declaring insert( ) function x = deque.insert(x, 22); // printing deque after inserting new element cout<< “ New Deque:”; for( x = deque.begin( ); x != deque.end( ); ++x) cout<< “ “ <<*x; return 0; }
輸出
如果執行上述程式碼,則會生成以下輸出
Input - Deque: 55 84 38 66 67 Output - New Deque: 22 55 84 38 66 67
示例
// C++ code to demonstrate the working of deque insert( ) function #include<iostream.h> #include<deque.h> Using namespace std; int main( ){ deque<char> deque ={ ‘B’ , ‘L’ , ‘D’ }; cout<< “ Deque: “; for( auto x = deque.begin( ); x != deque.end( ); ++x) cout<< *x << “ “; deque.insert(x + 1, 2, ‘O’); // printing deque after inserting new element cout<< “ New Deque:”; for( auto x = deque.begin( ); x != deque.end( ); ++x) cout<< “ “ <<*x; return 0; }
輸出
如果執行上述程式碼,則會生成以下輸出
Input – Deque: B L D Output – New Deque: B L O O D
示例
// C++ code to demonstrate the working of deque insert( ) function #include<iostream.h> #include<deque.h> #include<vector.h> Using namespace std; int main( ){ deque<int> deque ={ 65, 54, 32, 98, 55 }; cout<< “ Deque: “; for( auto x = deque.begin( ); x != deque.end( ); ++x) cout<< *x << “ “; vector<int7gt; v(3, 19); deque.insert(x, v.begin( ), v.end( ) ); // printing deque after inserting new element cout<< “ New Deque:”; for( auto x = deque.begin( ); x != deque.end( ); ++x) cout<< “ “ <<*x; return 0; }
輸出
如果執行上述程式碼,則會生成以下輸出
Input – Deque: 65 54 32 98 55 Output – New Deque: 65 19 19 19 65 54 32 98 55
廣告