如何在 C++ STL 列表中插入元素?
假设我们在 C++ 中有一个 STL 列表。其中有一些元素。我们需要在列表中插入一个新元素。我们可以在末尾、开头或任意位置进行插入。让我们看一个代码,以便更好地理解。要在开头插入,我们将使用 push_front(),要在末尾插入,我们将使用 push_end(),要在任意位置插入,我们需要使用一些操作。我们需要初始化一个迭代器,然后将该迭代器移到正确的位置,然后使用 insert() 方法进行插入。
示例
#include<iostream>
#include<list>
using namespace std;
void display(list<int> my_list){
for (auto it = my_list.begin(); it != my_list.end(); ++it)
cout << *it << " ";
}
int main() {
int arr[] = {10, 41, 54, 20, 23, 69, 84, 75};
int n = sizeof(arr)/sizeof(arr[0]);
list<int> my_list;
for(int i = 0; i<n; i++){
my_list.push_back(arr[i]);
}
cout << "List before insertion: ";
display(my_list);
//insert 100 at front
my_list.push_front(100);
//insert 500 at back
my_list.push_back(500);
//insert 1000 at index 5
list<int>::iterator it = my_list.begin();
advance(it, 5);
my_list.insert(it, 1000);
cout << "\nList after insertion: ";
display(my_list);
}输出
List before insertion: 10 41 54 20 23 69 84 75 List after insertion: 100 10 41 54 20 1000 23 69 84 75 500
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP