I would like to write a function to returning reference of iterator of an map entry in order to update the value of the entry. However, it fails at compile stage
#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 >&’ from expression of type ‘std::pair >’
return *(m.find(k));
^~~~~~~~~~~~