给定一个Set,任务是使用Iterator从此Set中删除一系列值。
例子:
Input: set = [10 20 30 40 50 60 70 80 90],
start_iterator = 3,
end_iterator = 8
Output: 10 20 80 90
Input: set = [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 Set by passing its value
#include
#include
using namespace std;
// Function to print the set
void printSet(set myset)
{
// Get the iterator
set::iterator it;
// printing all the elements of the set
for (it = myset.begin(); it != myset.end(); ++it)
cout << ' ' << *it;
cout << '\n';
}
// Function to delete the element of set
void deleteRange(set myset)
{
// printing all the elements of the set
cout << "\nSet originally: ";
printSet(myset);
// Get the starting Iterator at 3rd element
set::iterator start_itr = myset.begin();
start_itr++;
start_itr++;
// Get the ending Iterator at 2nd last element
set::iterator end_itr = myset.end();
end_itr--;
end_itr--;
// Erase the elements in the range
// of the iterators passed as the parameter
myset.erase(start_itr, end_itr);
// printing all the elements of the set
cout << "Set after deletion of range"
<< " from 3rd till 2nd last: ";
printSet(myset);
}
// Driver code
int main()
{
set myset;
// Get the set
for (int i = 1; i < 10; i++)
myset.insert(i * 10);
// Delete an element from the Set
deleteRange(myset);
return 0;
}
输出:
Set originally: 10 20 30 40 50 60 70 80 90
Set after deletion of range from 3rd till 2nd last: 10 20 80 90
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。