一、unordered_map
是一种容器,它存储的元素是键值对,并且基于哈希表实现。这意味着可以通过键快速查找对应的值,查找操作的平均时间复杂度为 O(1)。例如下面这个代码的键是string类型的,值是int 类型的。
二、代码
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
int main()
{
// 创建一个 unordered_map 容器,键为 string 类型,值为 int 类型
unordered_map<string, int> studentscores;
// 插入一些键值对
studentscores["Alice"] = 85;
studentscores["Bob"] = 92;
studentscores["Charlie"] = 78;
// 查找特定键的值
string name = "Bob";
auto it = studentscores.find(name);
if (it != studentscores.end())
{
cout << name << " 的分数是: " << it->second << endl;
}
else
{
cout << "未找到 " << name << " 的分数。" << endl;
}
return 0;
}
三、unordered_map跟vector一样都是容器。然后下面这条语句中的auto是C++11引入的一个关键字,用于自动推导变量的类型。在这个语句中,编译器会根据 studentScores.find(name)
的返回值类型来自动确定 it 的类型。这行代码的作用是在 studentscores
这个 unordered_map
容器中查找键为 name
的元素,并将指向该元素(如果找到)或指向 unordered_map
末尾(如果未找到)的迭代器赋值给变量 it
。后续可以通过检查 it
是否等于 studentscores.end()
来判断是否找到了指定键的元素。
auto it = studentscores.find(name);
四、it -> second 表示的是:it是一个迭代器 (可以理解为指针),first表示键,second表示值,it -> second 就是访问对应的值部分。
五、unordered_set
也是基于哈希表实现的容器,查找操作的平均时间复杂度同样是 O(1)。此代码创建了一个unordered_set
来存储整数,然后使用find
方法检查特定元素是否存在于集合里,并输出相应的结果。
六、代码
#include <iostream>
#include <unordered_set>
using namespace std;
int main()
{
// 创建一个 unordered_set 容器,存储 int 类型的元素
unordered_set<int> numbers = {1, 2, 3, 4, 5};
// 查找特定元素是否存在
int target = 3;
if (numbers.find(target) != numbers.end())
{
cout << target << " 存在于集合中。" << endl;
}
else
{
cout << target << " 不存在于集合中。" << endl;
}
return 0;
}
七、上面第一个程序unordered_map的时间复杂度分析:插入一些键值对对应的插入操作的时间复杂度是O(1);然后是find()函数的查找操作,因为它是基于哈希查找算法实现的,所以对应的时间复杂度是O(1);所以,整个程序的时间复杂度为O(1)。
八、上面的第二个程序unordered_set的时间复杂度分析:find()函数的查找操作也是基于哈希查找算法实现的,所以对应的时间复杂度也是O(1)。整个程序的时间复杂度为O(1)。