你这里使用了unordered_map不算使用STL容器么
时间: 2023-12-02 19:47:24 浏览: 32
抱歉,我在这里使用了unordered_map,它属于STL库中的容器之一。因此,上述实现中确实使用了STL容器。非STL容器的实现方式可能需要使用其他数据结构来替代unordered_map。我可以为您提供一种使用数组和链表来实现LRU Cache的方法,这样就不会使用STL容器。是否需要这种实现方式呢?
相关问题
unordered_set和unordered_map的基本使用
unordered_set和unordered_map是C++ STL中的容器,它们都是使用哈希表实现的,因此对于查找和插入操作来说,它们的时间复杂度为O(1)。
unordered_set是一个集合容器,其中存储的元素是唯一的,没有重复的元素。unordered_set中的元素是无序的,即元素在集合中的位置是随机的。
unordered_map是一个关联容器,其中存储的元素是成对的键值对。unordered_map中的元素是无序的,即键值对在容器中的位置是随机的。
unordered_set和unordered_map的基本用法如下:
unordered_set的定义和使用:
```c++
#include<unordered_set>
using namespace std;
int main()
{
unordered_set<int> s; // 定义一个unordered_set
s.insert(2); // 在集合中插入元素
s.insert(3);
s.insert(4);
s.erase(3); // 从集合中删除元素
if(s.count(2)) // 判断元素是否在集合中
cout<<"2 is in the set"<<endl;
for(auto x:s) // 遍历集合
cout<<x<<" ";
return 0;
}
```
unordered_map的定义和使用:
```c++
#include<unordered_map>
using namespace std;
int main()
{
unordered_map<int,string> m; // 定义一个unordered_map,键为int类型,值为string类型
m[1] = "one"; // 插入键值对
m[2] = "two";
m[3] = "three";
m.erase(2); // 删除键值对
if(m.count(1)) // 判断键是否在unordered_map中
cout<<"1 is in the map"<<endl;
for(auto x:m) // 遍历unordered_map
cout<<x.first<<" "<<x.second<<endl;
return 0;
}
```
C++ 如何使用unordered_map
unordered_map 是 C++ STL 中的一个关联容器,它提供了一种将键映射到值的方法。使用 unordered_map 需要包含头文件 <unordered_map>。
下面是一个简单的例子,展示了如何使用 unordered_map:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap;
// 插入元素
myMap.insert({"apple", 1});
myMap.insert({"banana", 2});
myMap.insert({"cherry", 3});
// 访问元素
std::cout << "apple: " << myMap["apple"] << std::endl;
std::cout << "banana: " << myMap["banana"] << std::endl;
std::cout << "cherry: " << myMap["cherry"] << std::endl;
// 修改元素
myMap["apple"] = 4;
// 删除元素
myMap.erase("banana");
// 遍历元素
for (auto& p : myMap) {
std::cout << p.first << ": " << p.second << std::endl;
}
return 0;
}
```
输出结果为:
```
apple: 1
banana: 2
cherry: 3
apple: 4
cherry: 3
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)