Files
leetcode/notes/src/stl_hash_table.md
2023-02-28 17:30:18 +08:00

45 lines
1.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 哈希表
```cpp
#include <iostream>
#include <string>
#include <unordered_map>
int main(int argc, const char *argv[]) {
// key 为 std::string 类型的value 为 int 类型的
std::unordered_map<std::string, int> map;
// 插入
map["foo"] = 1;
map["bar"] = 2;
map["non"] = 3;
// 访问
std::cout << map["foo"] << std::endl;
// 删除
map.erase("foo");
// 判断元素是否存在
if (map.count("bar") > 0) {
std::cout << "Exist" << std::endl;
} else {
std::cout << "Not exist" << std::endl;
}
// 另一种判断元素是否存在的方法
// find() 会返回元素的正向迭代器,如果没找到则返回 end()
if (map.find("bar") != map.end()) {
std::cout << "Exist" << std::endl;
} else {
std::cout << "Not exist" << std::endl;
}
// 合并两个 unordered_map
std::unordered_map<std::string, int> newMap;
newMap["microsoft"] = 1;
newMap["surface"] = 1;
map.insert(newMap.begin(), newMap.end());
// 遍历
for (std::unordered_map<std::string, int>::iterator iter = map.begin();
iter != map.end(); ++iter) {
std::cout << iter->first << iter->second << std::endl;
}
return 0;
}
```