STL-set (集合)之删除元素

2023-05-16

set概述


和vector、list不同,set、map都是关联式容器。set内部是基于红黑树实现的。插入和删除操作效率较高,因为只需要修改相关指针而不用进行数据的移动。 
在进行数据删除操作后,迭代器会不会失效呢?删除set的数据时,实际的操作是删除红黑树中的一个节点,然后相关指针做相关调整。指向其他元素的迭代器还是指向原位置,并没有改变,所以删除一个节点后其他迭代器不会失效。list和map也是同样的道理。然而删除vector中的某个元素,vector中其他迭代器会失效,因为vector是基于数组的,删除一个元素后,后面的元素会往前移动,所以指向后面元素的迭代器会失效。 
再稍微说一下迭代器的实现。迭代器是一个对象,vector的迭代器是封装了数组下标;list、map、set的迭代器是封装了元素节点的指针。 
还有一点,从数学层面,set的一个集合,好比一个袋子里面装了好多个小球。但是红黑树是一种特殊的二叉搜索树,set中的元素根据其值的大小在红黑树中有特定的位置,是不可移动的。所以,1是search操作效率会很高O(log n),2是set中元素的值不可改变。


set的数据操作

::begin()      //迭代器
::end()      //迭代器
::clear()     //删除set容器中的所有的元素
::empty()    //判断set容器是否为空
::max_size()  //返回set容器可能包含的元素最大个数
::size()    //返回当前set容器中的元素个数
::rbegin   //逆迭代器
::rend()  //逆迭代器

小问题
set是基于红黑树实现的,那么set的迭代器begin()、end()是指向哪里的呢? 
一个测试程序:

#include<iostream>
#include<set>
using namespace std;
int main()
{
    set<int> myset;
    myset.insert(4);
    myset.insert(7);
    myset.insert(2);
    myset.insert(0);
    myset.insert(4);
    set<int>::iterator it;
    for(it = myset.begin(); it != myset.end(); it++)
    {
        cout<< *it;   //输出结果是:0247
    }
}

红黑树首先是二叉搜索树,所以begin()迭代器指向红黑树的最左边的节点,end()迭代器指向红黑树的最右边的节点。另外这个小程序还说明了重复插入无效。


顺序删除

删除1-100间的奇数或偶数:

#include <iostream>
#include <cstdio>
#include <set>
#include <algorithm>
using namespace std;
int main()
{
    set<int>s;
    for(int i=100; i; i--)
        s.insert(i);
    set<int>::iterator it;
    for (it=s.begin(); it!=s.end(); it++)
    {
        cout<<*it<<" ";
    }
    cout<<"\n*********"<<endl;
    for (it=s.begin(); it!=s.end(); it++)
    {
        if(*it&1)
            s.erase(it);
    }
    cout<<"\n*********"<<endl;
    for (it=s.begin(); it!=s.end(); it++)
    {
        cout<<*it<<" ";
    }
    return 0;
}
此操作是能得到正确结果,但是方法正确吗?

如果要删除3的倍数时将会出现错误。

正确的应该怎么写呢?

#include <iostream>
#include <cstdio>
#include <set>
#include <algorithm>
using namespace std;
int main()
{
    set<int>s;
    for(int i=100; i; i--)
        s.insert(i);
    set<int>::iterator it;
    for (it=s.begin(); it!=s.end(); it++)
    {
        cout<<*it<<" ";
    }
    cout<<"\n*********"<<endl;
    int i=0;
    for (it=s.begin(); it!=s.end(); it++)
    {
        i++;
        if((*it)%3==0)
            s.erase(it++);
        else
            it++;
    }
    cout<<"\n*********"<<endl;
    for (it=s.begin(); it!=s.end(); it++)
    {
        cout<<*it<<" ";
    }
    return 0;
}

原因:STL/C++__中 set(集合)  删除元素, set的erase不会返回迭代器,这点需要注意。

参考博客:http://blog.csdn.net/doctor_feng/article/details/11836137


尊重原创,转载请注明出处:http://blog.csdn.net/hurmishine


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

STL-set (集合)之删除元素 的相关文章

随机推荐