unordered_map<int, int> map;
时间: 2023-11-04 21:55:28 浏览: 40
unordered_map是C++中的容器,用于存储键和对应的值。在这个例子中,unordered_map<int, int> map表示一个将int类型的键映射到int类型的值的unordered_map。通过map[key]的方式可以访问和操作unordered_map中的键值对。在方式一中,使用值传递遍历方式,将map中的键值对依次赋值给kv,并输出kv的first和second(即键和值)。
相关问题
unordered_map<char, int> 用法
unordered_map<char, int> 是 C++ STL 中的一个容器,用于存储键值对,其中键为 char 类型,值为 int 类型。它的用法类似于字典,可以通过键来访问对应的值。下面是一个简单的例子:
```c++
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<char, int> myMap;
myMap['a'] = 1;
myMap['b'] = 2;
myMap['c'] = 3;
cout << "The value of key 'a' is: " << myMap['a'] << endl;
cout << "The value of key 'b' is: " << myMap['b'] << endl;
cout << "The value of key 'c' is: " << myMap['c'] << endl;
return 0;
}
```
输出结果为:
```
The value of key 'a' is: 1
The value of key 'b' is: 2
The value of key 'c' is: 3
```
unordered_map<int, string>
`unordered_map<int, string>` 是 C++ 中的一种关联容器,它可以用来存储键值对,其中键的类型为 `int`,值的类型为 `string`。它提供了高效的插入、查找和删除操作,且不保证元素的顺序。
你可以使用 `unordered_map` 来实现基于整数键的字符串映射。例如,你可以将整数作为键,将相应的字符串作为值存储在 `unordered_map` 中。这样,你可以通过键快速查找、插入和删除对应的字符串。
下面是一个示例代码:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> myMap;
// 插入键值对
myMap[1] = "CSDN";
myMap[2] = "开发";
myMap[3] = "AI";
// 访问值
std::cout << myMap[1] << std::endl; // 输出 "CSDN"
// 修改值
myMap[2] = "技术";
// 删除键值对
myMap.erase(3);
// 遍历
for (const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
```
这段代码创建了一个 `unordered_map` 对象 `myMap`,并插入了三个键值对。然后,它访问了键为 1 的值,并修改了键为 2 的值。接着,它删除了键为 3 的键值对,并使用 `for` 循环遍历了整个 `unordered_map`,输出了所有的键值对。
希望这个示例能够帮助你理解 `unordered_map<int, string>` 的使用。如果你有任何进一步的问题,请随时提问!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)