当你在VS2013中想 引入greater,发现找不到,这个时候只要添加头文件#include <functional>即可,less是不需要的
// set练习.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include <set>
#include <functional> // std::greater
#pragma warning(disable:4996)
using namespace std;
class Student{
public:
Student(char *name, int age){
strcpy(this->name, name);
this->age = age;
}
public:
char name[64];
int age;
};
//仿函数的用法
struct FuncStudent{
bool operator()(const Student &left, const Student &right){
if (left.age < right.age){//如果左边的小 就返回真,从小到大按照年龄进行排序
return true;
}
else{
return false;
}
}
};
void playobj(){
//想按年龄排序
Student s1("s1",31);
Student s2("s2",22);
Student s3("s3",44);
Student s4("s4",11);
Student s5("s5",31);
set<Student, FuncStudent> stu;
stu.insert(s1);
stu.insert(s2);
stu.insert(s3);
stu.insert(s4);
//stu.insert(s5);//如果有两个31岁,能插入成功吗? 答案:不能!
//stu.erase(s5);//此时删除的是31岁那个 连s1也被删除了
//遍历
for (set<Student, FuncStudent>::iterator it = stu.begin(); it != stu.end();
it++){
cout << it->age << "\t" << it->name << endl;
}
}
void playobj2(){
set<int> st;
for (int i = 0; i < 10;i++){
st.insert(i);
}
set<int>::iterator it0 = st.find(5);
cout << "it0:" << *it0 << endl;//5
set<int>::iterator it1 = st.lower_bound(5);
cout << "it1:" << *it1 << endl;//5
set<int>::iterator it2 = st.upper_bound(5);
cout << "it2:" << *it2 << endl;//6
pair<set<int>::iterator, set<int>::iterator> mypair = st.equal_range(5);
set<int>::iterator it3 = mypair.first;
set<int>::iterator it4 = mypair.second;
cout << "it3:" << *it3 << endl;//5
cout << "it4:" << *it4 << endl;//6
}
int _tmain(int argc, _TCHAR* argv[])
{
set<int> set1;
//1.插入元素
for (int i = 0; i < 5; i++){
int tmp = rand();
set1.insert(tmp);
}
set1.insert(100);
set1.insert(100);
set1.insert(100);
for (set<int>::iterator it = set1.begin(); it != set1.end();it++){
cout << *it << " ";
}
//2.删除元素
while (!set1.empty()){
set<int>::iterator it = set1.begin();
cout << *it << " ";
set1.erase(set1.begin());
}
//3.能比较大小的set集合 默认从小到大
//现在想让其从大到小 进行
set<int> set11;//跟set12是一样的
set<int, less<int>> set12;//默认情况下是从小到大
set<int, greater<int>> set13;//从大到小
for (int i = 0; i < 5; i++){
int tmp = rand();
set13.insert(tmp);
}
//从大到小
for (set < int, greater<int>>::iterator it = set13.begin();
it != set13.end();it++){
cout << *it << endl;
}
//4.对于复杂的数据类型 Teacher Student
playobj();
playobj2();
return 0;
}