views:

315

answers:

4

Can I construct an std::map where the key type is a reference type, e.g. Foo & and if not, why not?

+2  A: 

No, because many of the functions in std::map takes a reference to the keytype and references to references are illegal in C++.

/A.B.

Andreas Brinck
+1  A: 

Consider the operator[](const key_type & key). If key_type is Foo & then what is const key_type &? The thing is that it does not work. You can not construct an std::map where the key type is a reference type.

Alexey Malistov
+8  A: 

According to C++ Standard 23.1.2/7 key_type should be assignable. Reference type is not.

Kirill V. Lyadvinsky
+1  A: 

Pointer as a key-type for std::map is perfectly legal

#include <iostream>
#include <cstdlib>
#include <map>

using namespace std;


int main()
{
int a = 2;
int b = 3;
int * c =  &a;
int * d =  &b;
map<int *, int> M;

M[c]=356;
M[d]=78;
return 0;
}

Initialised references cant be keys:

#include <iostream>
#include <cstdlib>
#include <map>

using namespace std;


int main()
{
int a = 2;
int b = 3;
int & c =  a;
int & d =  b;
map<int &, int> M;

M[c]=356;
M[d]=78;
return 0;
}
In file included from /usr/include/c++/4.4/map:60,
                 from test.cpp:3:
/usr/include/c++/4.4/bits/stl_tree.h: In instantiation of 'std::_Rb_tree<int&, std::pair<int&, int>, std::_Select1st<std::pair<int&, int> >, std::less<int&>, std::allocator<std::pair<int&, int> > >':
/usr/include/c++/4.4/bits/stl_map.h:128:   instantiated from 'std::map<int&, int, std::less<int&>, std::allocator<std::pair<int&, int> > >'
test.cpp:14:   instantiated from here
/usr/include/c++/4.4/bits/stl_tree.h:1407: error: forming pointer to reference type 'int&

'

Nadir SOUALEM
Keep in mind that ordering based on pointers is non-deterministic and likely to change with each invocation of the program.
Rob K
michalmocny