C++实用编程案例

自定义sort排序的编程案例:

#include<string>
#include<vector>
#include<stack>
#include <set>
#include <map>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;

class mem
{
public:
    mem() :_id(0), _name(""), _state(0){};
    mem(int id, string name, int state=0) :_id(id), _name(name), _state(state){};
    bool operator<(const mem& other)
    {
        if (this->_state&&!other._state)
            return false;
        if (!(this->_state) && other._state)
            return true;
        if (this->_id != other._id)
            return this->_id < other._id;
        else
        {
            return this->_name > other._name;
        }
    }
    void setState(int s)
    {
        _state = s;
    }
    string getName()
    {
        return _name;
    }
private:
    int _id;
    string _name;
    int _state;
};

void solution_2()
{
    int N;
    cin >> N;
    map<string, mem> mems;
    for (int i = 0; i < N; i++)
    {
        int id;
        string name;
        cin >> id >> name;
        mems[name]=mem(id, name);
    }
    int C;
    cin >> C;
    for (int i = 0; i < C; i++)
    {
        string name;
        int state;
        cin >> name >> state;
        mems[name].setState(state);
    }
    vector<mem> vec;
    for (pair<string, mem> pa : mems)
    {
        vec.push_back(pa.second);
    }
    sort(vec.begin(), vec.end());
    reverse(vec.begin(),vec.end());
    for (mem m : vec)
    {
        cout << m.getName() << endl;
    }
}


int main()
{
    solution_2();
    return 0;
}

自定义排序函数

bool compare(const int &odd1,const int &odd2)
{
	return odd1>odd2;
}

总结:注意自定义(operator<)sort中的排序方式,sort默认的是升序排序,当 “this<形参” 满足时,则返回true,否则返回false,这个规律和自定义排序函数相同,若返回odd1>odd2,则表示降序排序,从左往右看即可。

猜你喜欢

转载自blog.csdn.net/NichChen/article/details/81569674