2014-7-6 flyfish
在初始阶段会有大量数据增删改,而后期很少有更改,后期大部分是查询操作。
建立索引,使用排序的vector,使用二分法查找
以用户信息为例
用户信息包括,ID,名字,性别,手机号码
class CGender { public: enum { Female=0, Male=1, NotSpecified=2 }; }; class CUser { public: UINT64 m_nID; CString m_strName; int m_nGender; UINT64 m_nPhoneNumber; };
定义用户列表和索引
typedef std::pair<UINT64,std::shared_ptr<CUser>> USER;
建立针对用户操作的引擎
插入
根据ID查看是否存在该用户
根据ID查找用户
class CUserEngine { public: static std::vector<USER> m_vecUser; static void InsertUser(std::shared_ptr<CUser> p); static bool IsExist(UINT64 nID); static std::shared_ptr<CUser> QueryUserByID(UINT64 nID); };
//小ID在前 bool UserIDSort (const USER& a, const USER& b) { return (a.first < b.first); } void CUserEngine::InsertUser(std::shared_ptr<CUser> p) { m_vecUser.push_back(USER(p->m_nID,p)); std::sort(m_vecUser.begin(),m_vecUser.end(),UserIDSort); }
struct UserIDCompare { bool operator()(USER user, UINT64 nID) const { return user.first < nID; } bool operator()(UINT64 nID, USER user) const { return nID < user.first; } };
bool CUserEngine::IsExist(UINT64 nID) { return std::binary_search(m_vecUser.begin(),m_vecUser.end(),nID,UserIDCompare()); } std::shared_ptr<CUser> CUserEngine::QueryUserByID(UINT64 nID) { std::shared_ptr<CUser>p=nullptr; std::vector<USER>::iterator iter=std::lower_bound(m_vecUser.begin(),m_vecUser.end(),nID,UserIDCompare()); if (iter!=m_vecUser.end() && !(UserIDCompare()(nID,*iter))) { p=(*iter).second; } return p; }
//随机生成用户信息 std::default_random_engine dre; std::uniform_int_distribution<int> diGender(CGender::Female,CGender::NotSpecified); std::uniform_int_distribution<UINT64> diPhoneNUmber(10000000000,19999999999); for (int i=1;i<10;i++) { std::shared_ptr<CUser> p(new CUser()); p->m_nID=i; p->m_nGender=diGender(dre); p->m_nPhoneNumber=diPhoneNUmber(dre); CUserEngine::InsertUser(p); } for each(auto e in CUserEngine::m_vecUser) { //输出用户信息 } if(CUserEngine::IsExist(5)) { //查找是否存在ID为5的用户 } std::shared_ptr<CUser> p=CUserEngine::QueryUserByID(3); if (nullptr!=p) { //输入ID为3的用户信息 }
C++编程 – 快速查找一个对象,布布扣,bubuko.com
原文:http://blog.csdn.net/flyfish1986/article/details/37359317