STL自定义排序(sort)和自定义去重(unique)
-
自定义比较函数
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
class Link
{
public:
int a;
int b;
string str;
};
int main()
{
Link l1;
l1.a = 3;
l1.b = 4;
l1.str = "hello";
Link l2;
l2.a = 3;
l2.b = 2;
l2.str = "bye";
Link l3;
l3.a = 4;
l3.b = 5;
l3.str = "good";
Link l4;
l4.a = 4;
l4.b = 5;
l4.str = "good";
vector<Link> linkSet;
linkSet.push_back(l1);
linkSet.push_back(l2);
linkSet.push_back(l3);
linkSet.push_back(l4);
cout << "排序前:"<<endl;
//控制台输出
for (int i = 0; i<linkSet.size(); i++)
{
cout << linkSet[i].a << " " << linkSet[i].b << " " << linkSet[i].str.c_str() << " " << endl;
}
//自定义删除
auto cmp = [](Link x, Link y)
{
if (x.a == y.a)
return x.b < y.b;
return x.a < y.a;
};
sort (linkSet.begin(), linkSet.end(), cmp);
cout << "排序后:" << endl;
//控制台输出
for (int i = 0; i<linkSet.size(); i++)
{
cout << linkSet[i].a << " " << linkSet[i].b << " " << linkSet[i].str.c_str() << " " << endl;
}
//自定义删除
auto del= [](Link i, Link j)
{
return i.a == j.a && i.b ==j.b;
};
std::vector<Link>::iterator last;
last = unique(linkSet.begin(), linkSet.end(), del);
linkSet.erase(last, linkSet.end());
cout << "删除后:" << endl;
//控制台输出
for (int i = 0; i<linkSet.size(); i++)
{
cout << linkSet[i].a << " " << linkSet[i].b << " " << linkSet[i].str.c_str() << " " << endl;
}
system("pause");
return 0;
}
运行结果如下图
-
重载运算符,输出结果如上图
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
class Link
{
public:
int a;
int b;
string str;
};
inline bool operator<(const Link& s1, const Link& s2)
{
if (s1.a == s2.a)
return s1.b < s2.b;
return s1.a < s2.a;
}
inline bool operator==(const Link& s1, const Link& s2)
{
return s1.a == s2.a && s1.b == s2.b;
}
int main()
{
Link l1;
l1.a = 3;
l1.b = 4;
l1.str = "hello";
Link l2;
l2.a = 3;
l2.b = 2;
l2.str = "bye";
Link l3;
l3.a = 4;
l3.b = 5;
l3.str = "good";
Link l4;
l4.a = 4;
l4.b = 5;
l4.str = "good";
vector<Link> linkSet;
linkSet.push_back(l1);
linkSet.push_back(l2);
linkSet.push_back(l3);
linkSet.push_back(l4);
cout << "排序前:" << endl;
//控制台输出
for (int i = 0; i < linkSet.size(); i++)
{
cout << linkSet[i].a << " " << linkSet[i].b << " " << linkSet[i].str.c_str() << " " << endl;
}
//自定义
auto cmp = [](Link x, Link y)
{
if (x.a == y.a)
return x.b < y.b;
return x.a < y.a;
};
sort(linkSet.begin(), linkSet.end());
cout << "排序后:" << endl;
//控制台输出
for (int i = 0; i < linkSet.size(); i++)
{
cout << linkSet[i].a << " " << linkSet[i].b << " " << linkSet[i].str.c_str() << " " << endl;
}
//自定义删除
auto mycompare = [](Link i, Link j)
{
return i.a == j.a && i.b == j.b;
};
std::vector<Link>::iterator last;
last = unique(linkSet.begin(), linkSet.end());
linkSet.erase(last, linkSet.end());
cout << "删除后:" << endl;
//控制台输出
for (int i = 0; i < linkSet.size(); i++)
{
cout << linkSet[i].a << " " << linkSet[i].b << " " << linkSet[i].str.c_str() << " " << endl;
}
system("pause");
return 0;
}