STL容器 -- Set

核心: set 是一个数学含义上的集合-----保证了每个数的确定性, 互异性, 不仅如此, set 中的元素还是有序的.

头文件: #include <set>

拓展:由于 set 内的元素是唯一的, 即不会出现相同值的元素,所以无法存储重复值.如果要想存储重复值那么可以用 multiset.

构造方法:

set<int> s1; //定义一个 int 类型的set, 默认排序是从小到大的.
set<int> s2(s1); //定义一个 int 类型的set, 其初始值从集合 s1 拷贝而来.
int arv[] = {1, 2, 3, 4};
set<int> s3(arv, arv + 4); //利用迭代器 [ begin(), end() ) 里面的元素构建一个集合 

利用仿函数构造:

set< int, greater<int> > s1; //可以改变默认排序规则,按照降序排序

自定义比较函数构造:

const char* s[] = {"1", "2", "123232", "234", "321"};
struct cmp{
    bool operator () (const char* a, const char* b) const {
        return strcmp(a, b) > 0; //按照字典序降序排列
    }
};
set<const char*, cmp> s1(s, s + 5, cmp());

集合的遍历:

set<const char*, cmp>::iterator it;//迭代器类型和集合类型一致
for(it = s1.begin(); it != s1.end(); it++) {
    cout << *it << endl;
}

集合的插入:

 s1.insert(value);//插入value,返回pair配对对象,可以根据.second判断是否插入成功,有可能因为重复元素而插入失败  

集合的删除:

s1.erase(value)  //移除 s1 内元素值为value的所有元素,返回移除的元素个数  
s1.erase(&pos)  //移除pos位置上的元素,无返回值  
s1.erase(&first, &last)  //移除迭代器[&first, &last)区间内的元素,无返回值  
s1.clear()                     //移除容器 s1 内所有元素  

集合的查找:

s1.count(value);   //返回 s1 内元素值为value的元素个数, 为 ”1“ 或者 ”0“
s1.find(value);      //返回 s1 内 value 所在位置,找不到 value 将返回end();

自己定义类型必须重载 ”<“

struct NODE{
    int x; int y;
    bool operator < (const NODE& b) const {
        if(x == b.x) return y > b.y; //二级排序为 y 的降序
        return x < b.x; //一级排序为 x 的升序
    }
};
set<NODE> s1;

其他关于集合的操作:

s1.swap(s2);  //将集合 s1 和集合 s2 互换

//获得两个集合的 并
set<int> s1, s2, s3;
set_union(  s1.begin(),
                 s1.end(),
                 s2.begin(),
                 s2.end(),
                 insert_iterator< set<int> >(s3, s3.begin())
             );

//获得两个集合的 交
set<int> s1, s2, s3;
set_intersection( s1.begin(),
                         s1.end(),
                         s2.begin(),
                         s2.end(),
                         insert_iterator< set<int> >(s3, s3.begin())
                       );

//获得两个集合的 差
set<int> s1, s2, s3;
set_difference(   s1.begin(),     //set_symmetric_difference 为对称差 即 A  B - A  B
                         s1.end(),
                         s2.begin(),
                         s2.end(),
                         insert_iterator< set<int> >(s3, s3.begin())
                       );
原文地址:https://www.cnblogs.com/Ash-ly/p/5875104.html