C++中对typedef定义的map执行find/count操作出现编译错误是什么原因?
问题根因
你代码的核心错误是find返回值的接收类型写错了:std::map的find()成员函数返回的是对应map类型的迭代器,不是testAttribute_map类型本身。你在if判断里把接收find返回值的iter声明为testAttribute_map类型,编译器无法完成这两个完全不相关类型的转换,因此抛出了对应报错。
同时你也不能直接把迭代器放在if的判断条件中做隐式布尔转换,迭代器没有默认的布尔转换规则,只有找到目标后和end()迭代器比较才能判断是否查找成功。
修正后的代码示例
写法1:显式声明迭代器类型
testAttribute_map attributes; string fileName = "Hello.cpp"; testAttribute_map::iterator iter = attributes.find(fileName); if(iter != attributes.end()) { cout << "success" << endl; }
写法2:C++11及以上版本用auto简化类型声明
testAttribute_map attributes; string fileName = "Hello.cpp"; auto iter = attributes.find(fileName); if(iter != attributes.end()) { cout << "success" << endl; }
写法3:使用count判断(逻辑更简洁)
map的key全局唯一,count返回值只有0(未找到)和1(找到),可以直接用于布尔判断:
testAttribute_map attributes; string fileName = "Hello.cpp"; if(attributes.count(fileName)) { cout << "success" << endl; }
内容的提问来源于stack exchange,提问作者Amith Kotian
相关产品推荐
相关产品推荐

