加文

希望是美好的……
随笔 - 0, 文章 - 209, 评论 - 0, 引用 - 0
数据加载中……

list sort2

#include <iostream>
#include <iomanip>
#include <list>
#include <string>
using namespace std;

template <class T>
class Member
{
    public:
        Member(T f, T l) :
            first_n(f), last_n(l) {}
        void print();
    private:
        string last_n, first_n;
    // for sort() list member function
    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.c_str()
         << 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:\n"
     << "============================"
     << endl;

    list<M>::iterator It = li.begin();
    while ( It != li.end() )
    {
        (It++)->print();
    }
    cout << endl;

    li.sort();

    cout << "After sorting by last name:\n"
     << "============================"
     << endl;

    It = li.begin();
    while ( It != li.end() )
    {
        (It++)->print();
    }
    getchar();
    return 0;
}

posted on 2012-04-12 17:41 加文 阅读(107) 评论(0)  编辑 收藏 引用 所属分类: C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理