如何在C++中通过键值打印map中的完整键值对?
通过键值打印map对应键值对的实现方法
针对你给出的map<int, string> a = {{1, "one"}, {2, "two"}};,可以通过以下几种方式实现输入键值后打印完整键值对:
方法一:使用find()迭代器查找(推荐,不修改原map)
利用map的find()方法定位键值对,找到后直接输出键和对应值:
#include <iostream> #include <map> using namespace std; int main() { map<int, string> a = {{1, "one"}, {2, "two"}}; int targetKey; cout << "输入要查询的键值:"; cin >> targetKey; auto it = a.find(targetKey); if (it != a.end()) { cout << it->first << "," << it->second << endl; } else { cout << "该键值不存在于map中" << endl; } return 0; }
find()返回指向目标键值对的迭代器,若未找到则返回a.end()- 迭代器的
first成员对应键,second成员对应值
方法二:使用count()判断+[]访问
先通过count()判断键是否存在,存在则用[]取值输出:
#include <iostream> #include <map> using namespace std; int main() { map<int, string> a = {{1, "one"}, {2, "two"}}; int targetKey; cout << "输入要查询的键值:"; cin >> targetKey; if (a.count(targetKey)) { cout << targetKey << "," << a[targetKey] << endl; } else { cout << "该键值不存在于map中" << endl; } return 0; }
注意:
a[targetKey]如果遇到不存在的键,会自动在map中插入一个键为targetKey、值为空字符串的键值对,会修改原map的内容,所以如果不需要修改原map,优先用方法一。
内容的提问来源于stack exchange,提问作者Manav Roy
相关产品推荐
相关产品推荐

