C++编写返回map条目引用函数编译失败,寻求解决方法
问题:返回map条目引用以更新值时的编译错误
我想写一个返回map条目引用的函数,用来更新该条目的值,但代码编译失败。相关代码如下:
#include <map> #include <iostream> using namespace std; pair<int, string>& map_find(map<int,string>& m, int k){ return *(m.find(k)); } int main() { map<int,string> m; // insert an entry m.insert(make_pair<int,string>(128490,"def")); // search entry by key auto e = map_find(m,128490); cout << e.first << e.second<<endl;; e.second = "abc"; // Update value // verify if the entry is updated e = map_find(m,128490); cout << e.first << e.second<<endl;; return 0; }
编译错误信息:
main.cpp: In function ‘std::pair<int, std::__cxx11::basic_string<char> >& map_find(std::map<int, std::__cxx11::basic_string<char> >&, int)’: main.cpp:15:12: error: invalid initialization of reference of type ‘std::pair<int, std::__cxx11::basic_string<char> >&’ from expression of type ‘std::pair<const int, std::__cxx11::basic_string<char> >’ return *(m.find(k)); ^~~~~~~~~~~~
错误原因
std::map的键是不可修改的,所以它实际存储的条目类型是std::pair<const int, std::string>,而非你函数返回值声明的std::pair<int, std::string>&。这两种类型不兼容,导致引用初始化失败。
解决方法
- 修正函数返回类型,匹配
map实际存储的条目类型:std::pair<const int, std::string>&。 - 增加键存在性检查:
find方法找不到对应键时会返回end()迭代器,直接解引用会触发未定义行为,需提前判断并处理。 - 主函数中接收返回值时要使用引用(
auto&),否则会拷贝条目,后续修改的只是拷贝而非原map中的数据。
修正后的代码
#include <map> #include <iostream> #include <stdexcept> using namespace std; pair<const int, string>& map_find(map<int,string>& m, int k){ auto it = m.find(k); if (it == m.end()) { throw invalid_argument("Key not found in map"); } return *it; } int main() { map<int,string> m; // insert an entry m.insert(make_pair<int,string>(128490,"def")); // search entry by key (用引用接收,避免拷贝) auto& e = map_find(m,128490); cout << e.first << " " << e.second << endl; e.second = "abc"; // 修改原map中的条目值 // 验证更新结果 auto& updated_e = map_find(m,128490); cout << updated_e.first << " " << updated_e.second << endl; return 0; }
内容的提问来源于stack exchange,提问作者David Tong
相关产品推荐
相关产品推荐

