# c++容器 set 自定义排序

set c++ reference是c++中的一种容器，set可以用二叉树搜索树实现，set有两个特点：

1. set中的元素不允许重复；

2. set内部会维护一个严格的弱排序关系。

# 默认定义了compare函数

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

int main() {
int a[] = {20,10,30,40,50};
set<int> s1(a, a + 5);
for (auto it = s1.cbegin(); it != s1.cend(); it++)
{
cout << *it << " ";
}
cout << endl;

string b[] = {"apple", "banana", "pear", "orange", "strawberry"};
set<string> s2(b, b + 5);
for (auto it = s2.cbegin(); it != s2.cend(); it++)
{
cout << *it << " ";
}
cout << endl;
system("pause");
return 0;
}

10 20 30 40 50
apple banana orange pear strawberry

# 自定义排序函数

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

struct intComp {
bool operator() (const int& lhs, const int& rhs) const{
return lhs > rhs;
}
};

struct strComp
{
bool operator() (const string& str1, const string& str2) const {
return str1.length() < str2.length();
}
};

int main() {
int a[] = {10, 20, 30, 40, 50};
set<int, intComp> s1(a, a + 5);
for (auto it = s1.cbegin(); it != s1.cend(); it++)
{
cout << *it << " ";
}
cout << endl;

string b[] = {"apple", "banana", "pear", "orange", "strawberry"};
set<string, strComp > s2(b, b + 5);
for (auto it = s2.cbegin(); it != s2.cend(); it++)
{
cout << *it << " ";
}
cout << endl;
system("pause");
return 0;
}

50 40 30 20 10
pear apple banana strawberry