unordered_map是基于哈希表的C++关联容器,提供O(1)平均时间复杂度的查找、插入和删除操作,适用于无需排序的快速访问场景。

unordered_map 是 C++ STL 中提供的关联容器,用于存储键值对(key-value pairs),其底层基于哈希表实现,查找、插入和删除操作的平均时间复杂度为 O(1)。相比 map(基于红黑树,有序),unordered_map 无序但访问更快,适合需要快速查找的场景。
使用 unordered_map 需要包含头文件 <unordered_map>,并使用 std 命名空间:
#include <iostream>声明一个 unordered_map 的格式为:
unordered_map<Key_Type, Value_Type> map_name;
常见用法示例:
立即学习“C++免费学习笔记(深入)”;
unordered_map<string, int> ageMap; // 键为字符串,值为整数支持的初始化方式:
以下是一些核心操作及对应函数:
下面是一个完整的小程序演示 unordered_map 的典型用法:
#include <iostream>int main() {
  unordered_map<string, int> studentAges = {
    {"Alice", 20},
    {"Bob", 22},
    {"Charlie", 19}
  };
  // 插入新元素
  studentAges["David"] = 21;
  // 查找并输出 Bob 的年龄
  auto it = studentAges.find("Bob");
  if (it != studentAges.end()) {
    cout << "Bob's age: " << it->second << endl;
  }
  // 遍历输出所有学生信息
  for (const auto& s : studentAges) {
    cout << s.first << " - " << s.second << " years old" << endl;
  }
  return 0;
}
基本上就这些。掌握 unordered_map 能显著提升查找效率,是算法题和工程开发中的常用工具。
以上就是c++++怎么使用unordered_map_c++中unordered_map的用法与示例解析的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
 
                 
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号