C++ 如何使用迭代器从列表中删除一定范围的值
给定一个列表,任务是使用迭代器从列表中删除一定范围的值。
例如:
输入: list = [10 20 30 40 50 60 70 80 90],
start_iterator = 3,
end_iterator = 8
输出: 10 20 80 90
输入: list = [1 2 3 4 5]
start_iterator = 1,
end_iterator = 3
输出: 3 4 5
C++
建议:在转到解决方案之前,请先在{IDE}上尝试自己的方法。
做法: 在此方法中,从列表中删除了一定范围的元素。这是通过两个迭代器完成的。第一个迭代器指向范围的起始元素,而第二个迭代器指向范围的最后一个元素。第一个迭代器是独占的,而最后一个迭代器是包容的,这意味着最后一个迭代器指向的元素也将被删除。
语法:
iterator erase (const_iterator startPositionIterator_exclusive,
const_iterator endingPositionIterator_inclusive);
C++
下面是实现以上方法的代码:
程序:
// C++ program to delete an element
// of a List by passing its value
#include <iostream>
#include <list>
using namespace std;
// Function to print the list
void printList(list<int> mylist)
{
// Get the iterator
list<int>::iterator it;
// printing all the elements of the list
for (it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
cout << '\n';
}
// Function to delete the element of list
void deleteRange(list<int> mylist)
{
// Printing all the elements of the list
cout << "\nList originally: ";
printList(mylist);
// Get the starting Iterator at 3rd element
list<int>::iterator start_itr = mylist.begin();
start_itr++;
start_itr++;
// Get the ending Iterator at 2nd last element
list<int>::iterator end_itr = mylist.end();
end_itr--;
end_itr--;
// Erase the elements in the range
// of the iterators passed as the parameter
mylist.erase(start_itr, end_itr);
// Printing all the elements of the list
cout << "List after deletion of range"
<< " from 3rd till 2nd last: ";
printList(mylist);
}
// Driver Code
int main()
{
list<int> mylist;
// Get the list
for (int i = 1; i < 10; i++)
mylist.push_back(i * 10);
// Delete an element from the List
deleteRange(mylist);
return 0;
}
C++
List originally: 10 20 30 40 50 60 70 80 90
List after deletion of range from 3rd till 2nd last: 10 20 80 90
C++