• list-sort2


    ////////////////////////////////////////
    //      2018/04/27 7:36:05
    //      list-sort2
    
    // sorts with user datatype
    #include <iostream>
    #include <iomanip>
    #include <list>
    #include <string>
    
    using namespace std;
    
    template<class T>
    class Member{
    private:
        T last_n, first_n;
    public:
        Member(T f, T l) :first_n(f), last_n(l){}
        void print();
    
        // 注意: 由于有两个参数,全局重载
        friend bool operator < (Member& m1, Member& m2){
            return m1.last_n < m2.last_n;
        }
    };
    //------------------
    template<class T>
    void Member<T>::print(){
        cout.setf(ios::left);
        cout << setw(15) << last_n << " " << first_n << endl;
    }
    
    typedef Member<string> M;
    //========================
    
    int main(){
        list<M> li;
        li.push_back(M("Linda", "Smith"));
        li.push_back(M("Frost", "Robert"));
        li.push_back(M("Alex","Amstrong"));
    
        cout << "Before sorting by last name:
    ";
        cout << "==============================" << endl;
    
        list<M>::iterator it = li.begin();
        while (it != li.end()){
            (it++)->print();
        }
        cout << endl;
    
        li.sort();
    
        cout << "After sorting by last name:
    ";
        cout << "==========================" << endl;
    
        it = li.begin();
        while (it != li.end()){
            (it++)->print();
        }
        cout << endl;
    
        return 0;
    }
    
    
    /*
    OUTPUT:
        Before sorting by last name:
        ==============================
        Smith           Linda
        Robert          Frost
        Amstrong        Alex
    
        After sorting by last name:
        ==========================
        Amstrong        Alex
        Robert          Frost
        Smith           Linda
    */
  • 相关阅读:
    [荐]推荐一个shell学习的网站
    [转]linux远程登入不需要密码
    [转] eclipce使用vim 开启装逼模式
    Linux 下查找指令
    nmon 工具的使用
    LaTeX 符号大全
    vim 粘贴复制操作
    linux命令模式下如何切换首行和尾行
    fish 与oh-my-fish 的安装
    vim 粘贴复制操作
  • 原文地址:https://www.cnblogs.com/laohaozi/p/12537932.html
Copyright © 2020-2023  润新知