c++ map 用value输出key
时间: 2024-05-03 22:19:02 浏览: 118
在 C++ 的 map 中,可以通过迭代器遍历 map 的键值对,然后输出对应的键和值。以下是一个示例代码:
```c++
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> m;
// 添加几个键值对
m[1] = "one";
m[2] = "two";
m[3] = "three";
// 遍历 map,输出键值对
for (auto it = m.begin(); it != m.end(); ++it) {
std::cout << "key: " << it->first << ", value: " << it->second << std::endl;
}
// 根据 value 输出对应的 key
std::string value_to_find = "two";
for (auto it = m.begin(); it != m.end(); ++it) {
if (it->second == value_to_find) {
std::cout << "key with value '" << value_to_find << "': " << it->first << std::endl;
}
}
return 0;
}
```
输出结果为:
```
key: 1, value: one
key: 2, value: two
key: 3, value: three
key with value 'two': 2
```
阅读全文