[关闭]
@breakerthb 2017-01-05T02:16:23.000000Z 字数 985 阅读 1051

STL - set

C/C++


Set

底层使用平衡的搜索树(红黑树)实现,插入删除操作时仅仅需要指针操作节点即可完成,不涉及到内存移动和拷贝,所以效率比较高。

1. 常用操作:

1.1 元素插入

insert()

1.2 中序遍历

类似vector遍历(用迭代器)

1.3 反向遍历

利用反向迭代器reverse_iterator。

set<int> s;
    ......
    set<int>::reverse_iterator rit;
    for(rit = s.rbegin(); rit != s.rend(); rit++)

1.4 元素删除

与插入一样,可以高效的删除,并自动调整使红黑树平衡。

set<int> s;
s.erase(2);        //删除键值为2的元素
s.clear();

1.5 元素检索

find(),若找到,返回该键值迭代器的位置,否则,返回最后一个元素后面一个位置。

set<int> s;
set<int>::iterator it;
it=s.find(5);    //查找键值为5的元素
if(it != s.end())    //找到
    cout << *it << endl;
else            //未找到
    cout << "未找到";

1.6 自定义比较函数

(1)元素不是结构体:

//自定义比较函数myComp,重载“()”操作符
struct myComp
{
    bool operator()(const your_type &a,const your_type &b)
    [
        return a.data-b.data>0;
    }
}
set<int,myComp>s;
......
set<int,myComp>::iterator it;

(2)如果元素是结构体,可以直接将比较函数写在结构体内。

struct Info
{
    string name;
    float score;
    //重载“<”操作符,自定义排序规则
    bool operator < (const Info &a) const
    {
        //按score从大到小排列
        return a.score<score;
    }
}
set<Info> s;
......
set<Info>::iterator it;
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注