Logo

C++harsh

C++harsh

harsh map

类别功能描述语法示例
头文件包含 unordered_map 的定义#include <unordered_map>#include <unordered_map>
声明声明一个 unordered_map 对象std::unordered_map<KeyType, ValueType> mapName;std::unordered_map<std::string, int> ages;
插入元素unordered_map 中插入键值对mapName[key] = value;mapName.insert({key, value});mapName.emplace(key, value);ages["Alice"] = 30; ages.insert({"Bob", 25}); ages.emplace("Charlie", 35);
访问元素通过键访问对应的值mapName[key]mapName.at(key)int aliceAge = ages["Alice"]; int bobAge = ages.at("Bob");
查找元素检查 unordered_map 中是否存在某个键mapName.count(key)mapName.find(key)if (ages.count("Alice")) { /* 键存在 */ } auto it = ages.find("Bob"); if (it != ages.end()) { /* 键存在,值是 it->second */ }
删除元素unordered_map 中删除指定的键值对mapName.erase(key)mapName.erase(iterator)mapName.erase(begin_iterator, end_iterator)ages.erase("Charlie"); auto it = ages.find("Bob"); if (it != ages.end()) { ages.erase(it); } ages.erase(ages.begin(), ages.end());
判空检查 unordered_map 是否为空mapName.empty()if (ages.empty()) { /* map 为空 */ }
获取大小获取 unordered_map 中键值对的数量mapName.size()size_t numElements = ages.size();
迭代器遍历 unordered_map 中的所有键值对mapName.begin(), mapName.end(), mapName.cbegin(), mapName.cend()cpp for (const auto& pair : ages) { std::cout << pair.first << ": " << pair.second << std::endl; }
清空移除 unordered_map 中的所有元素mapName.clear()ages.clear();
键类型要求作为键的类型需要支持相等比较 (==) 和计算哈希值 (std::hash)任何满足这些要求的类型都可以作为键std::string, int, char 等内置类型,以及自定义的类(需要重载 == 并提供 std::hash 的特化版本)
无序性元素在 unordered_map 中没有特定的顺序(不同于 std::map插入顺序和遍历顺序可能不一致注意在需要有序遍历时,unordered_map 不是合适的选择。

© 2025 All rights reservedBuilt with Flowershow Cloud

Built with LogoFlowershow Cloud