map::iterator it = map.find(key); if(it != map.end()) { it->first; // key it->second; // value }
so, add new item, we can do it like this:
if(map.end() == map.find(key)) { map[key] = value; }
demo:
std::map<int, std::string> map001;
map001[1] = "001";
map001[2] = "002";
map001[3] = "003";
map001[4] = "004";
map001[5] = "005";
int map_key = 1;
if (map001.end() != map001.find(map_key)) {
printf("find pair, key: %d, value: %s\n", map_key, map001[map_key].c_str());
map001.erase(map_key);
}
std::map<int, std::string>::const_iterator map_it = map001.find(2);
if (map_it != map001.end()) {
printf("find pair, key: %d, value: %s\n", map_it->first, map_it->second.c_str());
map001.erase(map_it);
}
std::for_each(map001.begin(), map001.end(), [&](const std::pair<int, std::string>& item) {
printf("key: %d, value: %s\n", item.first, item.second.c_str());
});
代码库:map用例(Server类)
2.1 hash相关概念
参考文档:
2.2 std::hash_map
参考文档: C++中使用STL的hashmap
2.2.1 std::hash_map<std::string, ..>
#include <string>
#include <hash_map>
#include <iostream>
using namespace std;
class T_ {
public:
T_(int a = 0) : m_nNum(a) {}
private:
int m_nNum;
};
struct string_less : public binary_function<std::string, std::string, bool> {
public:
result_type operator()(const first_argument_type& _Left, const second_argument_type& _Right) const {
return(_Left.compare(_Right) < 0 ? true : false);
}
};
int main() {
std::hash_map<std::string, T_*, hash_compare<std::string, string_less>> hmp2;
hmp2["123"] = new T_(12);
hmp2["456"] = new T_(15);
if(hmp2.end() == hmp2.find("123")) {
hmp2["123"] = new T_(12);
}
return 0;
}
2.2.2 std::hash_map<自定义类, ..>
#include <string>
#include <hash_map>
#include <iostream>
using namespace std;
/* interface */
class IHashable {
public:
virtual ~IHashable() {} // virtual destructor
virtual size_t hash_value() const = 0; // pure virtual funciton
virtual bool operator<(const IHashable& val) const = 0; // pure virtual funciton
};
class CTest : public IHashable
{
public:
CTest(int value = 0, const std::string& message = "")
: m_value(value), m_message(message) {}
~CTest() {}
// 哈希函数,可以采用其他哈希算法
virtual size_t hash_value() const {
return ((size_t)m_value ^ _HASH_SEED);
}
virtual bool operator<(const IHashable& val) const {
return (m_value < ((CTest&)val).m_value);
}
private:
int m_value;
std::string m_message;
};
template<class _Tkey>
class HashCompare : public hash_compare<_Tkey>
{
public:
size_t operator()(const _Tkey& _Key) const {
return(_Key.hash_value());
}
bool operator()(const _Tkey& _Keyval1, const _Tkey& _Keyval2) const {
return (this->_Getcomp()(_Keyval1, _Keyval2));
}
};
int main() {
std::hash_map<CTest, std::string, HashCompare<IHashable>> hmp;
hmp[CTest(10, "helloworld")] = "12306";
if(hmp.end() == hmp.find(CTest(8, "wonderful"))) {
hmp[CTest(8, "wonderful")] = "12308";
}
return 0;
}
备注: 上述例子如需深入研究,需要具体分析STL源码,此处篇幅有限,不详述。
2.3 哈希函数
参考文档: 常见的hash函数
参考文档: