学了一段STL,深为它的精巧所折服。 一个习作,还请高人指点,看何处还可以改进。
rtdb 2003-04-11 01:49:09 程序主要功能:按名(名不可重复)管理一个状态字链表。
#include "stdafx.h"
#include <string>
#include <list>
#include <algorithm>
#include <iostream>
#include <fstream>
using namespace std;
class CKeyUser : public string
{
public:
string m_Status ;
CKeyUser(string name, string status):string(name), m_Status(status){};
bool operator == (const string& rh)
{
return string(*this) == rh ;
}
bool operator > (const string& rh)
{
return string(*this) > rh ;
}
bool operator < (const string& rh)
{
return string(*this) < rh ;
}
};
class CUserList : public list<CKeyUser>
{
public:
/* add a user, if user exist, update its status */
void Add(string name, string status)
{
list<CKeyUser>::iterator it ;
it = find(begin(), end(), name) ;
if ( it == end())
{
CKeyUser cUser(name, status) ;
push_back(cUser) ;
}
else
it->m_Status = status ;
}
void Del(string name)
{
list<CKeyUser>::iterator it ;
it = find(begin(), end(), name) ;
if ( it != end())
erase(it) ;
}
};
ostream& operator << (ostream &cout, CUserList& cList)
{
cout << endl << "Current list:" << endl;
list<CKeyUser>::iterator it ;
for ( it = cList.begin(); it != cList.end(); it++)
{
cout << "status: " << it->m_Status << " key: " << string(*it) << endl ;
}
return cout ;
}
int main(int argc, char* argv[])
{
cout << "Hello World!" << endl ;
CUserList cList ;
cList.Add("aaa", "1") ;
cList.Add("bbb", "2") ;
cList.Add("ccc", "3") ;
cList.Add("ddd", "4") ;
cout << cList ;
cList.Add("aaa", "11") ;
cList.Add("bbb", "22") ;
cout << cList ;
cList.Del("bbb") ;
cout << cList ;
cList.Del("ddd") ;
cout << cList ;
ofstream of("test.txt") ;
of << cList ;
return 0;
}