C++ Foundation —— (16) C++14 set (Not translated)
»
    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

«
--Alex.Zhang
--www.v-signon.com Learningers Co-Encouraged
Back
Personal Art: www.up-task.com Unit: Individual
中文 Русский 京ICP备19038994号-2
If the content on this website infringes upon your any rights, please contact me at 1307776259@qq.com for removal