C++ STL 中的 list insert()
本任務演示 C++ STL 中 list insert() 函式的功能。
什麼是 STL 中的 List
List 是一種容器,允許在序列中的任何位置進行常數時間插入和刪除操作。List 以雙向連結串列的形式實現。List 允許非連續記憶體分配。與陣列、向量和雙端佇列相比,List 在容器的任何位置執行元素的插入、提取和移動操作的效率更高。在 List 中,對元素的直接訪問速度較慢,並且 List 與 forward_list 類似,但 forward list 物件是單向連結串列,只能向前迭代。
什麼是 insert()
list insert() 函式用於在列表中插入元素。
該函式用於在指定位置插入元素。
該函式還用於在列表中插入 n 個元素。
它還用於在指定位置插入指定範圍內的元素。
語法
insert(iterator position, const value_type& val) insert(iterator position, size_type n, const value_type& value) insert(iterator position, iterator first, iterator last)
引數
Val - 指定要插入列表中的新元素。
Position - 指定在容器中插入新元素的位置。
n - 要插入的元素數量。
First, last - 指定迭代器,用於指定要插入的元素範圍。
返回值
它返回一個迭代器,指向第一個新插入的元素。
示例
輸入 列表 - 50 60 80 90
輸出 新列表 - 50 60 70 80 90
輸入 列表 - T R E N D
輸出 新列表 - T R E N D S
可遵循的方法
- 首先,我們宣告列表
然後我們列印列表。
然後我們宣告 insert() 函式。
使用上述方法,我們可以在列表中插入新元素。新元素應與列表具有相同的資料型別。
示例
/ / C++ code to demonstrate the working of list insert( ) function in STL #include<iostream.h> #include<list.h> Using namespace std; int main ( ){ List<int> list = { 55, 84, 38, 66, 67 }; / / print the deque cout<< “ List: “; for( auto x = List.begin( ); x != List.end( ); ++x) cout<< *x << “ “; / / declaring insert( ) function list.insert( x, 6); / / printing new list after inserting new element cout<< “New list “; for( x=list.begin( ); x != list.end( ); ++x) cout<< “ “<<*x; return 0; }
輸出
如果我們執行以上程式碼,則會生成以下輸出
Input - List: 55 84 38 66 67 Output - New List: 6 84 38 66 67
示例
/ / C++ code to demonstrate the working of list insert( ) function in STL #include<iostream.h> #include<list.h> Using namespace std; int main( ){ List<char> list ={ ‘F’, ‘B’, ‘U’, ‘A’, ‘R’, ‘Y’ }; cout<< “ List: “; for( auto x = list.begin( ); x != list.end( ); ++x) cout<< *x << “ “; / / declaring insert( ) function list.insert(x + 1, 1, ‘E’); / / printing new list after inserting new element cout<< “ New List:”; for( auto x = list.begin( ); x != list.end( ); ++x) cout<< “ “ <<*x; return 0; }
輸出
如果我們執行以上程式碼,則會生成以下輸出
Input – List: F B U A R Y Output – New List: F E B U A R Y
示例
/ / C++ code to demonstrate the working of list insert( ) function in STL #include<iostream.h> #include<list.h> #include<vector.h> Using namespace std; int main( ){ list<int> list ={ 10, 44, 34, 98, 15 }; cout<< “ list: “; for( auto x = list.begin( ); x != list.end( ); ++x) cout<< *x << “ “; vector<int> l(2, 17); list.insert(x, l.begin( ), l.end( ) ); / / printing new list after inserting new element cout<< “ New list:”; for( auto x = list.begin( ); x != list.end( ); ++x) cout<< “ “ <<*x; return 0; }
輸出
如果我們執行以上程式碼,則會生成以下輸出
Input – List: 10 44 34 98 15 Output – New list: 17 17 10 44 34 98 15
廣告