»
(16)C++14 set
(18)C++14 智能指针及引用计数*
(19)C++14 多线程pthread*
(20)C++14 同步锁mutex*
(24)C++中的计时与等待*
(25)C++中的高精度计算*
(27)C++14 std::string*
(31)C++高级技能*
C++中的set是一个有序集合。放入set中的对象只需要实现operator <操作符重载,就可以实现对象在set中的唯一性判断。想想为什么呢?
因为,<操作符,一个操作符,既可以用来判断A>B是否成立,也可以用来判断B>A是否成立,如果都不成立,那就得到了A与B相等的结果。
set的例子代码:
#include <iostream>
#include <set>
typedef enum{
UNCONFIRMED=0,
MALE=1,
FEMALE=2
}Gender;
using namespace std;
class RowItem{
private:
int id;
string name;
Gender gender;
public:
RowItem(int id, string name, Gender gender){
this->id=id;
this->name=std::move(name);
this->gender=gender;
}
bool operator < (const RowItem& right) const{
return this->name<right.name;
}
void print() const{
cout<<this->id<<" "<<this->name<<" "<<this->gender<<endl;
}
};
int main(){
RowItem rowItem1(1,"NotSortName1",MALE);
RowItem rowItem2(2,"001SortName2",FEMALE);
RowItem rowItem3(3,"Name3",MALE);
set<RowItem>rowItemSet;
rowItemSet.insert(rowItem1);
rowItemSet.insert(rowItem1);
rowItemSet.insert(rowItem2);
rowItemSet.insert(rowItem2);
rowItemSet.insert(rowItem3);
rowItemSet.insert(rowItem3);
rowItemSet.insert(rowItem3);
cout<<"RowItem Set:"<<endl;
for(auto& rowItem:rowItemSet){
rowItem.print();
}
return 0;
}
打印结果:
RowItem Set:
2 001SortName2 2
3 Name3 1
1 NotSortName1 1