
set的基本 *** 作:
clear() 清除所有元素
count() 返回某个值元素的个数
empty() 如果集合为空,返回true
end() 返回指向最后一个元素的迭代器
equal_range() 返回集合中与给定值相等的上下限的两个迭代器
erase() 删除集合中的元素
find() 返回一个指向被查找到元素的迭代器
get_allocator() 返回集合的分配器
insert() 在集合中插入元素
lower_bound() 返回指向大于(或等于)某值的第一个元素的迭代器
key_comp() 返回一个用于元素间值比较的函数
max_size() 返回集合能容纳的元素的最大限值
rbegin() 返回指向集合中最后一个元素的反向迭代器
rend() 返回指向集合中第一个元素的反向迭代器
size() 集合中元素的数目
swap() 交换两个集合变量
upper_bound() 返回大于某个值元素的迭代器
value_comp() 返回一个用于比较元素间的值的函数
5,自定义比较函数:
For example:
#include<iostream>#include<set>
using namespace std
typedef struct {
int a,b
char s
}newtype
struct compare //there is no ().
{
bool operator()(const newtype &a, const newtype &b) const
{
return a.s<b.s
}
}//the “ ” is here
set<newtype,compare>element
int main()
{
newtype a,b,c,d,t
a.a=1 a.s='b'
b.a=2 b.s='c'
c.a=4 c.s='d'
d.a=3 d.s='a'
element.insert(a)
element.insert(b)
element.insert(c)
element.insert(d)
set<newtype,compare>::iterator it
for(it=element.begin() it!=element.end()it++)
cout<<(*it).a<<" "
cout<<endl
for(it=element.begin() it!=element.end()it++)
cout<<(*it).s<<" "
}
element自动排序是按照char s的大小排序的;
6.其他的set构造方法;
#include <iostream>#include <set>
using namespace std
bool fncomp (int lhs, int rhs) {return lhs<rhs}
struct classcomp {
bool operator() (const int& lhs, const int& rhs) const
{return lhs<rhs}
}
int main ()
{
set<int> first // empty set of ints
int myints[]= {10,20,30,40,50}
set<int> second (myints,myints+5) // pointers used as iterators
set<int> third (second) // a copy of second
set<int> fourth (second.begin(), second.end()) // iterator ctor.
set<int,classcomp> fifth // class as Compare
bool(*fn_pt)(int,int) = fncomp
set<int,bool(*)(int,int)> sixth (fn_pt) // function pointer as Compare
return 0
}
没考虑性能,仅供参考。public static void main(String[] args) {List<Set<String lists = new ArrayList<Set<String() {{add(new HashSet<String(Arrays.asList("apple", "banana")))add(new HashSet<String(Arrays.asList("ball", "pen")))add(new HashSet<String(Arrays.asList("apple", "orange")))add(new HashSet<String(Arrays.asList("grape", "orange")))add(new HashSet<String(Arrays.asList("paper", "ruler")))add(new HashSet<String(Arrays.asList("ink", "pen")))}}System.out.println(merge(lists))}public static List<Set<String merge(List<Set<String lists) {List<Set<String result = new ArrayList<Set<String()Map<String, Set<String map = new HashMap<String, Set<String()for (Set<String list : lists) {// 寻找类似的列表。Set<String simList = nullfor (Entry<String, Set<String e : map.entrySet()) {if (list.contains(e.getKey())) {simList = e.getValue()simList.addAll(list)// 合并类似。break}}// 没找到类似。if (simList == null) {result.add(list)// 结果中加入引用。simList = list}// 已经合并过了,所以不再区分。for (String s : list) {欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)