C/C++教程

c++笔记 STL set容器_内置类型指定排序规则

本文主要是介绍c++笔记 STL set容器_内置类型指定排序规则,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
//set容器默认排序为从小到大,掌握如何改变排序规则
//利用仿函数,可以改变排序规则
#include<iostream>
#include<set>
using namespace std;
//仿函数:用类调用函数
//仿函数设计:
class MyCompare {
public:
	//下一行末尾加上const
	/*bool operator()(int v1, int v2){
		return v1 > v2;
	}*/
	bool operator()(int v1, int v2)const {
		return v1 > v2;
	}
};
void test01() {
	set<int>s1;
	s1.insert(10);
	s1.insert(40);
	s1.insert(30);
	s1.insert(50);
	s1.insert(20);
	for (set<int>::iterator it = s1.begin(); it != s1.end(); it++) {
		cout << *it << " ";
	}
	cout << endl;

	//指定排序规则为从大到小
	//重新指定第一步,更改第二个默认值
	//注意:这里第二个默认值需求为类型,不可以是函数(函数名),故使用仿函数
	set<int,MyCompare>s2;
	s2.insert(10);
	s2.insert(40);
	s2.insert(30);
	s2.insert(50);
	s2.insert(20);
	for (set<int, MyCompare>::iterator it = s2.begin(); it != s2.end(); it++) {
		cout << *it << " ";
	}
	cout << endl;
}
int main() {
	test01();
}

这篇关于c++笔记 STL set容器_内置类型指定排序规则的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!