leetcode/notes/src/stl_hash_table.md

1.1 KiB
Raw Blame History

哈希表

#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;
}