C ++ STL 中的 unordered_set erase () 函数
unordered_set::erase() 函数是 C++ STL 中的一个内置函数,用于删除单个元素或从开始(包括)到结束(不包括)的一组元素。这会减小容器的大小,删除元素的数量。
注意 :unordered_set 中的桶从0到n-1编号,其中n是桶的总数。
语法 :
有三种声明方法,
方法(1):unordered_set_name.erase(iterator start, iterator end)
方法(2):unordered_set_name.erase(iterator position)
方法(3):unordered_set_name.erase(element)
复杂度:
平均情况: 线性的 在删除元素的数量(对于Method(2)和Method(3)来说是 恒定的 )。
最坏的情况: 线性的 在容器大小。
参数: 该函数接受三种类型的参数。如果它接受一个单独的元素,则找到该特定元素并删除它们。如果它接受一个迭代器,则删除该位置上的元素。如果它接受两个迭代器开始和结束,则删除范围 [start,end] 中的所有元素
返回值 : 在前两个语法的情况下,此函数返回指向已擦除的最后一个元素之后的元素的迭代器。在第三种语法的情况下,如果 unordered_set 中不存在该元素,则返回0,否则在删除元素之后返回1。
下面的程序说明了 unordered_set::erase() 函数:
程序1 :
// CPP program to illustrate the
// unordered_set::erase() function
 
#include <iostream>
#include <unordered_set>
 
using namespace std;
 
int main()
{
 
    unordered_set<int> sampleSet;
 
    // 插入元素
    sampleSet.insert(5);
    sampleSet.insert(10);
    sampleSet.insert(15);
    sampleSet.insert(20);
    sampleSet.insert(25);
 
    // 通过其位置擦除特定元素
    sampleSet.erase(sampleSet.find(10));
 
    // 删除一系列元素
    sampleSet.erase(sampleSet.begin(), sampleSet.end());
 
    cout << "删除后的集合:";
    for (auto it = sampleSet.begin(); it != sampleSet.end(); it++) {
        cout << *it << " ";
    }
 
    cout << "\n集合的大小: " << sampleSet.size();
 
    return 0;
}  
输出 :
25 5 15 20  
集合的大小: 0
程序2 :
// CPP program to illustrate the
// unordered_set::erase() function
 
#include <iostream>
#include <string>
#include <unordered_set>
 
using namespace std;
 
int main()
{
 
    unordered_set<string> sampleSet = { "geeks1", "for", "geeks2" };
 
    // 删除一个特定元素
    sampleSet.erase("geeks1");
// 删除后的元素
    cout << "元素: ";
    for (auto it = sampleSet.begin(); it != sampleSet.end(); it++) {
        cout << *it << " ";
    }
    sampleSet.insert("geeks1");
    // 从元素 for 开始删除
    sampleSet.erase(sampleSet.find("for"), sampleSet.end());
    // 删除后的元素
    cout << "\n第二次删除后的元素: ";
    for (auto it = sampleSet.begin(); it != sampleSet.end(); it++) {
        cout << *it << " ";
    }
    return 0;
}  
输出 :
元素: geeks2 for 
第二次删除后的元素: geeks1 geeks2 
极客教程