What is the alternative if I need to use a reference, and the data I am passing I cannot change the type of, hence I cannot really store a pointer to it?
Code:
#include <map>
#include<iostream>
#include<string>
using namespace std;
int main()
{
string test;
pair<string, string> p=pair<string, string>("Foo","Bar");
map<pair<string, string>, string&> m;
m[make_pair("aa","bb")]=test;
return 0;
}
Error:
$ g++ MapPair.cpp
/usr/include/c++/3.2.3/bits/stl_map.h:
In instantiation of
std::map<std::pair<std::string,std::string&’ MapPair.cpp: In
std::string>, std::string&,
std::less<std::pair<std::string,
std::string> >,
std::allocator<std::pair<const
std::pair<std::string, std::string>,
std::string&> > >': MapPair.cpp:15:
instantiated from here
/usr/include/c++/3.2.3/bits/stl_map.h:221:
forming reference to reference type
functionint main()': MapPair.cpp:16:std::map, std::string&,
no match for
std::less >,
std::allocator,
std::string&> > >& [std::pair]’ operator
/usr/include/c++/3.2.3/bits/stl_pair.h:
At global scope:
/usr/include/c++/3.2.3/bits/stl_pair.h:
In instantiation ofstd::pair<conststd::_Rb_tree_node
std::pair<std::string, std::string>,
std::string&>':
/usr/include/c++/3.2.3/bits/stl_tree.h:122:
instantiated from
What am I doing wrong to cause this errror?
You cannot store references. References are just aliases to another variable.
The map needs a copy of the string to store:
The reason you are getting that particular error is because somewhere in map, it’s going to do an operation on the
mapped_typewhich in your case isstring&. One of those operations (like inoperator[], for example) will return a reference to themapped_type:Which, with your
mapped_type, would be:And you cannot have a reference to a reference:
On a side note, I would recommend you use
typedef‘s so your code is easier to read:}