multiset搬运
原作者:https://www.cnblogs.com/wenzhixin/p/8509909.html
额外:https://blog.csdn.net/sodacoco/article/details/84798621
································································································································································
更新:有点点需要注意:https://blog.csdn.net/chenyijun/article/details/118892856
#include <set>
#include <string>
#include <iostream>
using namespace std;
struct myComp{
bool operator () (const string &a,const string &b){
if(a.compare(b) == 1)
return 1;
return 0;
}
};
struct STUDENT{
string name;
double score;
//重载"<"运算符,自定义排列规则
bool operator < (const STUDENT &a) const{
return a.score<score;//由大到小。如果由小到大,则符号为>
}
};
void print(multiset<string> ms);
void rprint(multiset<string> ms);
int main()
{
//多重集合的创建与插入
multiset<string> ms;
ms.insert("abc");
ms.insert("123");
ms.insert("111");
ms.insert("aaa");
ms.insert("123");
cout<<"中序正向遍历:\n";
print(ms);
cout<<"中序逆向遍历:\n";
rprint(ms);
/*运行结果
中序正向遍历:
111
123
123
aaa
abc
中序逆向遍历:
abc
aaa
123
123
111
*/
//元素的查找
/*同set集合容器一样,使用find()查找元素,如果找到返回钙元素的迭代器位置(如果该元素存在重复,则返回第
一个重复元素的迭代器位置),否则,返回end()迭代器*/
multiset<string>:: iterator it;
it=ms.find("123");
if(it != ms.end()) cout<<"找到键值为123的元素\n";
it=ms.find("456");
if(it == ms.end()) cout<<"没有找到键值为456的元素\n";
/*运行结果
找到键值为123的元素
没有找到键值为456的元素
*/
//多重集合元素的删除
cout<<"删除前:\n";
print(ms);
int n=ms.erase("123");//删除键值等于某个值得所有重复元素,并返回删除元素的个数
cout<<"删除了"<<n<<"个元素\n";
cout<<"删除后:\n";
print(ms);
/*运行结果
删除前:
111
123
123
aaa
abc
删除了2个元素
删除后:
111
aaa
abc
*/
ms.clear();
if(ms.empty()) cout<<"清除后为:空\n";
/*运行结果
清除后为:空
*/
/*同样在使用insert()可以采用自定义比较函数,默认从小到大*/
//当元素类型是基本数据类型时,采用在主函数前重载"()"操作符
multiset<string,myComp> mss;
mss.insert("abc");
mss.insert("123");
mss.insert("111");
mss.insert("aaa");
mss.insert("123");
multiset<string>::iterator it1;
for(it1= mss.begin(); it1 != mss.end(); it1 ++){
cout<<*it1<<endl;
}
/*运行结果
abc
aaa
123
123
111
*/
//如果元素是结构体,可以将比较函数写在结构体内,见main函数之前的定义方法
multiset<STUDENT> students;
STUDENT someone;
someone.name="Jack";
someone.score=80.5;
students.insert(someone);
someone.name="Tomi";
someone.score=57.5;
students.insert(someone);
someone.name="Nacy";
someone.score=60.5;
students.insert(someone);
someone.name="Nacy";
someone.score=60.5;
students.insert(someone);
multiset<STUDENT>:: iterator it2;
for(it2 = students.begin(); it2 != students.end(); it2 ++){
cout<<(*it2).name<<":"<<(*it2).score<<endl;
}
/*运行结果
Jack:80.5
Nacy:60.5
Nacy:60.5
Tomi:57.5
*/
return 0;
}
void print(multiset<string> ms)
{
multiset<string>:: iterator it;
for(it=ms.begin(); it != ms.end(); it ++){
cout<<*it<<endl;
}
}
void rprint(multiset<string> ms)
{
multiset<string>::reverse_iterator rit;
for(rit=ms.rbegin(); rit != ms.rend(); rit++){
cout<<*rit<<endl;
}
}