set 和 multiset函数
创建对象
set<T>s; //创建一个空集合,默认升序;T为类型
set<T,op>// op即操作{
升序 set<int,greater<int>()>s2;//注意在个别情况需要加#include<functional> 注意geater为降序,less为升序;
降序 set<int,less<int>()>s2;
}
set<T,op>s(begin,end) begin,end为初始化区间;
set<T>s(s1);//用s1初始化s;
自定义比较函数
(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;
部分操作相同
s.size();
s.empty();
s.max_size();
不同操作
set s.find(elem);//返回该元素位置;
元素检索:find(),若找到,返回该键值迭代器的位置,否则,返回最后一个元素后面一个位置。
set<int> s;
set<int>::iterator it;
it=s.find(5); //查找键值为5的元素
if(it!=s.end()) //找到
cout<<*it<<endl;
else //未找到
cout<<"未找到";
但是在multiset中用两种方法取代find();
http://www.cnblogs.com/scut-fm/p/3224558.html
第一种 使用lower_bond();和upper_bond();
set.lower_bound(elem);//返回第一个>=elem元素的迭代器
set.upper_bound(elem);//返回第一个>elem元素的迭代器
********第二种 equal_rang()函数//还不会********
set.equal_range(elem);//返回两个迭代器,一个指向>=elem的元素;另一个指向>elem的元素。两个迭代器被封装在一个pair中。
http://blog.youkuaiyun.com/glp_hit/article/details/8112794//此为equal用法
迭代器
普通操作
遍历操作
#include
#include
using namespace std;
void TestSet()
{
set s;
for (int i = 0; i < 10; ++i)
{
s.insert(i);
}
set::reverse_iterator it = s.rbegin();//用反向迭代器接收
while (it != s.rend())
{
cout << *it << " ";
++it;//使用++从前向后遍历
}
cout << endl;
}
int main()
{
TestSet();
system("pause");
return 0;
}
插入和删除
插入
删除
set.clear();//清除所有元素
set.erase(pos);//删除pos位置的元素,返回下一个元素的位置(迭代器)
set.erase(beg, end);//删除区间[beg, end)的元素,返回下一个元素的迭代器
set.erase(elem);//删除容器中值为elem的元素
pair
pair 通常作为map的迭代器出现的吧
map<string, int> word_count;
pair<string,int> p_count;
p_count = make_pair("word",3);//make_pair(),返回一个pair类型
cout << p_count.first << endl; //输出p_count的key,也就是"word";
cout << p_count.second << endl; //输出p_count的value,也就是3
word_count.insert(make_pair("word1",2));
map<string, int>::iterator mit;
mit = word_count.begin();
cout << mit->first << endl;
cout << mit->first << endl; //分别输出“word1”,和2
set s;
for (int i = 1; i < 10; i += 2)
{
s.insert(i);
}
set::iterator it = s.begin();
while (it != s.end())
{
cout << *it << " ";
++it;
}
cout << endl;
pair::iterator, set::iterator> ret = s.equal_range(3);
cout << "pair.first:lower_bound:" << *ret.first << endl;
cout << "pair.second:upper_bound:" << *ret.second << endl;