STL——容器(Set & multiset)的删除 erase
set.clear(); //清除所有元素
set.erase(pos); //删除pos迭代器所指的元素,返回下一个元素的迭代器。
set.erase(beg,end); //删除区间[beg,end)的所有元素,返回下一个元素的迭代器。
set.erase(elem); //删除容器中值为elem的元素。
代码例子:
#include <iostream>
#include <set>
using namespace std;
int main()
{
    set<int> setInt;
    cout << "第一次遍历setInt,没有任何元素:";
    for (set<int>::iterator it = setInt.begin(); it != setInt.end(); it++)
    {
        cout << *it << " ";
    }
    //在容器中插入元素
    cout << endl << "插入20个元素" << endl << endl;
    for (int i = 0; i < 20; i++)
    {
        setInt.insert(i);
    }
    cout << "插入20个元素后的第二次遍历setInt" << endl;
    for (set<int>::iterator it = setInt.begin();it!=setInt.end(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;
    
    //删除迭代器所指的元素,返回下一个元素的迭代器。
    cout << "删除迭代器所指的元素 5 " << endl;
    for (set<int>::iterator it = setInt.begin(); it != setInt.end();)
    {
        if (*it == 5)
        {
            it = setInt.erase(it);        //由于会返回下一个元素的迭代器,相当于进行了it++的操作
        }
        else
        {
            it++;
        }
    }
    cout << endl << "删除迭代器所指的元素 5 后遍历 setInt:" << endl;
    for (set<int>::iterator it = setInt.begin();  it != setInt.end(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;
    //删除区间(beg,end)的所有元素,返回下一个元素的迭代器。
    cout << endl << "删除元素 15 之后的所有元素";
    for (set<int>::iterator it = setInt.begin(); it != setInt.end();)
    {
        if (*it == 15)
        {
            //如果找到15,删除15之后所有的元素,由于会返回下一个元素的迭代器,相当于进行了it++的操作
            it = setInt.erase(it, setInt.end());
        }
        else
        {
            it++;
        }
    }
    cout << endl << "删除元素 15 之后的所有元素后遍历 setInt:";
    for (set<int>::iterator it = setInt.begin(); it != setInt.end(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;
    // 删除容器中值为elem的元素
    cout << endl << "删除元素 10";
    setInt.erase(10);
    cout << endl << "删除元素 10 之后遍历 setInt:";
    for (set<int>::iterator it = setInt.begin(); it != setInt.end(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;
    //清除所有元素
    cout << endl << "删除所有元素";
    setInt.clear();    
    cout << endl << "删除所有元素之后遍历 setInt:";
    for (set<int>::iterator it = setInt.begin(); it != setInt.end(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;
    return 0;
}打印结果:

==================================================================================================================================
相关推荐
  容数据服务集结号    2020-06-08  
   CoderBoy    2020-03-03  
   kong000dao0    2020-04-29  
   yuanye0    2020-03-03  
   kong000dao0    2020-03-02  
   vipiter    2020-02-22  
   JnX    2020-09-21  
   joyjoy0    2020-09-18  
   Jan    2020-08-17  
   shenxiuwen    2020-08-01  
   Andrewjdw    2020-07-26  
   fanhuasijin    2020-06-21  
   czsay    2020-06-01  
   程序员之怒    2020-04-26  
   wmsjlihuan    2020-04-26  
   oDongTianShuiYue    2020-04-26  
   breakpoints    2020-04-20  
   卷卷萌    2020-04-20  
 