12.3 自定义规则的multiset

#include<iostream>
#include<algorithm>
#include<set>
using namespace std;

struct rule{
	bool operator()(const &a1, const &a2)
	{
		return a1%10 < a2%10;
	}
};

int main()
{
	int a[10] = {2,6,210,8,5,9,12,8,9,122};
	int n = sizeof(a)/sizeof(int);
	
	multiset<int,greater<int> > st1;
	for(int j = 0; j < n; ++j)
		st1.insert(a[j]);
	multiset<int,greater<int> >::iterator i;
	for(i = st1.begin(); i != st1.end(); ++i)//210 122 12 9 9 8 8 6 5 2 
		cout << *i << " "; 
	cout << endl;
	i = st1.find(8);
	cout << *i << endl;
	
	multiset<int,rule> st2;
	for(int j = 0; j < n; ++j)
		st2.insert(a[j]);
	multiset<int,rule>::iterator p;
	for(p = st2.begin(); p != st2.end(); ++p)// 210 2 12 122 5 6 8 8 9 9  
		cout << *p << " "; 
	cout << endl;
	p = st2.find(1222);
	cout << *p << endl;//2
	return 0;
}

【注意】这里2 12 122的顺序并不是固定的,谁排在谁前面都可以,因为rule规则里面只定义了个位数从小到大排列,并没有说个位数相等该如何排列,所以最后计算机输出的结果不一定是严格按照2 12 122 的顺序的。

这里要注意p和i都是迭代器,要访问multiset中的元素,必须要使用迭代器,迭代器的作用类似于指针,指向某个数所在的位置。

p = st2.find(1222)这里因为rule规则只用比较个位数的大小,查找的数并不一定要==,只要找到某个数在1222前面或者后面都可以,就算找到了,并不是严格的相等关系。

在使用multiset<int,greater<int> > st;时,治理greater<int> >,后面两个“>”之间有两个空格。

在p=st.find(s)中,因为在定义的排序规则中,s排在“85 Mary 102”的前面或者后面都可以,那就可以说能找到s,数据是相等的。

#include<iostream>
#include<cstring>
#include<set>
using namespace std;

struct Student{
	char name[20];
	int id;
	int score;
};

Student a[] = {{"Jack",112,78},{"Mary",102,85},{"Ala",333,92},{"Zero",101,70},{"Cindy",102,78}};
struct rule{
	bool operator()(const Student &a1, const Student &a2)
	{
		if(a1.score != a2.score)
			return a1.score > a2.score;
		else
			return strcmp(a1.name,a2.name)<0;
	}
}; 

int main()
{
	int n = sizeof(a)/sizeof(Student);
	multiset<Student,rule> st;
	for(int i = 0; i < n; ++ i)//插入的过程就自动排好序了 
		st.insert(a[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 s1 = {"Mary",134,85};
	Student s2 = {"Mary",134,100};
	p = st.find(s1);
	if(p != st.end())
		cout << p->score << " " << p->name << " " << p->id << endl;
	else
		cout << "not found" << endl;
	p = st.find(s2);
	if(p != st.end())
		cout << p->score << " " << p->name << " " << p->id << endl;
	else
		cout << "not found" << endl;
	return 0;	
}

猜你喜欢

转载自blog.csdn.net/yanyanwenmeng/article/details/82424478