map详讲<二>
作者:互联网
查找元素:
Map可以根据健来查找元素,提供方法find(key),如果是这个健对应的元素存在,则返回的是这个健的迭代器iterator,否则返回的是std::end(); 使用find()函数有点笨拙,但是还是必须的有时候,如果是只想知道有木有这个健对应的元素,则可以使用count(key),因为是map所以键值是唯一的,count(key)返回的是这个健的元素个数
在map中返回1表示存在这个元素,0表示不存在这个元素。
删除元素:
map也提供erase(key);删除对应键值的元素;
插入实例:
#include <iostream> #include <map> class BankInfo { public: BankInfo():mID(0),mName(""){} BankInfo(int id,const std::string& name) :mID(id),mName(name) { } void setID(int id){mID = id;} int getID(){return mID;} void setName(std::string name) {mName = name;} std::string getName() {return mName;} private: int mID; std::string mName; }; class BankDB { public: bool addAcount(BankInfo dbInfro); void delAcount(int key); BankInfo& getKey(int key); BankInfo& getName(const std::string& name); private: std::map<int,BankInfo> mClients; }; bool BankDB::addAcount(BankInfo dbInfro) { auto ret = mClients.insert(std::make_pair(dbInfro.getID(),dbInfro)); if(ret.second) { return true; } return false; } void BankDB::delAcount(int key) { mClients.erase(key); } BankInfo& BankDB::getKey(int key) { auto ret = mClients.find(key); if(ret == std::end(mClients)) { throw std::out_of_range("out of range"); } return ret->second; } BankInfo& BankDB::getName(const std::string& name) { auto ret = std::begin(mClients); for(;ret != std::end(mClients);++ret) { if(ret->second.getName() == name) { return ret->second; } } throw std::out_of_range("out of range"); } int main() { BankDB db; db.addAcount(BankInfo(1,"abc")); db.addAcount(BankInfo(2,"bcd")); db.addAcount(BankInfo(3,"cde")); try { auto ret = db.getKey(1); std::cout << "key[" << ret.getID() << "]" << " "; std::cout << "value :" << ret.getName() << std::endl; auto ret1 = db.getName("cde"); std::cout << "key[" << ret1.getID() << "]" << " "; std::cout << "value :" << ret1.getName() << std::endl; auto ret2 = db.getName("dfe"); std::cout << "key[" << ret2.getID() << "]" << " "; std::cout << "value :" << ret2.getName() << std::endl; }catch (const std::out_of_range&) { std::cout << "Not find this value" << std::endl; } return 0; }
结果是:
key[1] value :abc
key[3] value :cde
Not find this value
标签:std,map,详讲,mClients,int,BankInfo,ret,key 来源: https://www.cnblogs.com/boost/p/10412986.html