📌  相关文章
📜  如何使用迭代器从列表中删除值的范围

📅  最后修改于: 2021-05-30 01:55:07             🧑  作者: Mango

给定一个列表,任务是使用迭代器从此列表中删除一系列值。

例子:

Input: list = [10 20 30 40 50 60 70 80 90],
       start_iterator = 3,
       end_iterator = 8
Output: 10 20 80 90

Input: list = [1 2 3 4 5]
       start_iterator = 1,
       end_iterator = 3
Output: 3 4 5

方法:在这种方法中,从列表中删除了一系列元素。这是在两个迭代器的帮助下完成的。第一个迭代器指向范围的起始元素,第二个迭代器指向范围的最后一个元素。第一个迭代器是唯一的,而最后的迭代器是包容性的,这意味着元素也将被删除它是由过去的迭代器尖。

句法:

iterator erase (const_iterator startPositionIterator_exclusive, 
                const_iterator endingPositionIterator_inclusive);

下面是上述方法的实现:

程序:

// C++ program to delete an element
// of a List by passing its value
  
#include 
#include 
using namespace std;
  
// Function to print the list
void printList(list mylist)
{
    // Get the iterator
    list::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 mylist)
{
    // Printing all the elements of the list
    cout << "\nList originally: ";
    printList(mylist);
  
    // Get the starting Iterator at 3rd element
    list::iterator start_itr = mylist.begin();
    start_itr++;
    start_itr++;
  
    // Get the ending Iterator at 2nd last element
    list::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 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;
}
输出:
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++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”