Set
类型名称:set<T>
或是set<T,Ordering>
,表明由T类型的元素构成的一个set,Ordering用于对元素进行排序,以便存储,如果没有指定,默认为 <
头文件:<set>
已定义类型包括:value_type、size_type
迭代器:iterator、const_iterator、reverse_iterator、const_reverse_iterator
,所有迭代器都是双向的,除了const_修饰的都是可变的,begin()、end()、rbegin()、rend()
具有预期的行为,一般的增删元素不影响迭代器,除非定位的是要删除的元素。
成员函数:
• s.insert(元素)
:将元素的一个副本插入set,不能重复插入相同的元素,而set中的a和b重复 : “a必须排在 b前面” 前面” 和“ b必须排在 a前面”都不成立
• s.erase(元素)
:从set中删除元素,没有则没有任何效果
• s.find(元素)
:返回一个可变迭代器,它定位到set中的元素的一个副本,如果元素不在set中则返回s.end()
• s.erase(迭代器)
:删除迭代器定位的位置处的元素
• s.size()
:返回set的元素数量
• s.empty()
:判断set是否为空
• s1==s2
:如果set中包含相同的元素就返回true,否则返回false
此外还有一个默认的构造函数、一个拷贝构造函数以及其他特殊的构造函数,还有一个析构函数。
使用set的例子:
#include <iostream>
#include <set>
using namespace std;
int main( )
{
set<char> s;
s.insert('A');
s.insert('D');
s.insert('D');
s.insert('C');
s.insert('C');
s.insert('B');
cout << "The set contains:\n";
set<char>::const_iterator p;
for (p = s.begin( ); p != s.end( ); p++)
cout << *p << " ";
cout << endl;
cout << "Removing C.\n";
s.erase('C');
for (p = s.begin( ); p != s.end( ); p++)
cout << *p << " ";
cout << endl;
return 0;
}
输出为:
Multiset
基本上定义的一些内容和set相差不同,只是不要求multiset的数据不必不得重复; 对于set<T,Ordering>
中的Ordering
可以不使用默认的排序规则,也可以自定义排序规则。 例如我们设置从大到小排序输出:
#include <iostream>
#include <set>
using namespace std;
int main()
{
multiset<int,greater<int> > st; //规定排序规则从大到小,注意> >中必须有空格,否则编译不通过
for(int i=0;i<9;i++){
st.insert(i);
}
multiset<int,greater<int> >::iterator p;
for(p=st.begin();p!=st.end();p++){
cout<<*p<<" ";
}
cout<<endl;
return 0;
}
输出如下:
除了int等类型外,还可以使用自定义的类型,例如:
#include <iostream>
#include <set>
#include <cstring>
#include <algorithm>
using namespace std;
struct Student{
char name[20];
int id;
int score;
};
Student students [] = {{"Jack",112,78},{"Mary",102,85},{"Ala",333,92},{"Zero",101,70},{"Cindy",102,78}};
struct Rule{
bool operator() (const Student &s1,const Student &s2){
if(s1.score!=s2.score)
return s1.score>s2.score; //成绩从大到小
else
return(strcmp(s1.name,s2.name)<0); //名字按字典序从小到大排列
}
};
int main()
{
multiset<Student,Rule> st;
for(int i=0;i<5;i++)
st.insert(students[i]); //插入的是Students[i]的复制品
multiset<Student,Rule>::iterator p;
for(p=st.begin();p!=st.end();p++)
cout<<p->score<<" "<<p->name<<" "<<p->id<<endl;
cout<<endl;
Student s={"Mary",1000,85};
p=st.find(s);
if(p!=st.end())
cout<<p->score<<" "<<p->name<<" "<<p->id<<endl;
return 0;
}
输出为:
感谢慕课上北京大学郭炜老师的算法课程,老师讲的很有趣哦!