list :: erase()是C++ STL中的内置函数,用于从列表容器中删除元素。此函数可用于从指定的列表容器中删除单个元素或一系列元素。
句法:
iterator list_name.erase(iterator position)
or,
iterator list_name.erase(iterator first, iterator last)
参数:该函数可以接受不同的参数,具体取决于它是用于从列表容器中擦除单个元素还是一系列元素。
- position :当该函数用于删除单个元素时,使用此参数。此参数引用一个迭代器,该迭代器指向需要从列表容器中删除的元素。
- first , last :当列表用于擦除范围中的元素时,将使用这两个参数。参数first指向该范围内第一个元素的迭代器,参数last指向该范围内需要删除的最后一个元素的迭代器。这会删除在包括元件的范围内的所有元素指出由迭代第一但不包括元件指出通过最后的迭代器。
返回值:该函数返回一个迭代器,该迭代器指向列表容器中的元素,该元素之后是从列表容器中删除的最后一个元素。
下面的程序说明了list :: erase()函数。
程序1 :删除单个元素。
// CPP program to illustrate the
// list::erase() function
#include
using namespace std;
int main()
{
// Creating a list
list demoList;
// Add elements to the List
demoList.push_back(10);
demoList.push_back(20);
demoList.push_back(30);
demoList.push_back(40);
demoList.push_back(50);
// Printing elements of list before deleting
// first element
cout << "List before deleting first element: ";
for (auto itr = demoList.begin();
itr != demoList.end(); itr++) {
cout << *itr << " ";
}
// Creating iterator to point to first
// element in the list
list::iterator itr = demoList.begin();
// deleting the first element
demoList.erase(itr);
// Printing elements of list after deleting
// first element
cout << "\nList after deleting first element:";
for (auto itr = demoList.begin();
itr != demoList.end(); itr++) {
cout << *itr << " ";
}
return 0;
}
输出:
List before deleting first element: 10 20 30 40 50
List after deleting first element:20 30 40 50
程序2 :删除一系列元素。
// CPP program to illustrate the
// list::erase() function
#include
using namespace std;
int main()
{
// Creating a list
list demoList;
// Add elements to the List
demoList.push_back(10);
demoList.push_back(20);
demoList.push_back(30);
demoList.push_back(40);
demoList.push_back(50);
// Printing elements of list before deleting
// any element
cout << "List before deleting any element: ";
for (auto itr = demoList.begin();
itr != demoList.end(); itr++) {
cout << *itr << " ";
}
// Creating iterators of the list
list::iterator itr1, itr2;
itr1 = demoList.begin();
itr2 = demoList.begin();
// Incrementing itr2 by 3 positions
advance(itr2, 3);
// deleting range of elements from index [0, 3)
demoList.erase(itr1, itr2);
// Printing elements of list after deleting
// range of elements from [0, 3)
cout << "\nList after deleting first three elements: ";
for (auto itr = demoList.begin();
itr != demoList.end(); itr++) {
cout << *itr << " ";
}
return 0;
}
输出:
List before deleting any element: 10 20 30 40 50
List after deleting first three elements: 40 50
注意:此函数以线性时间复杂度工作,即从列表容器中删除的元素数。
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。