Can I construct an std::map
where the key type is a reference type, e.g. Foo &
and if not, why not?
Asked
Active
Viewed 4,798 times
21

davetapley
- 17,000
- 12
- 60
- 86
-
1+1 this is a good question that many are afraid to ask. – laura Nov 25 '09 at 10:52
-
3Not directly, but `boost::reference_wrapper
` should work. It has an implicit conversion to `Foo&` – MSalters Nov 26 '09 at 10:11
4 Answers
16
According to C++ Standard 23.1.2/7 key_type
should be assignable. Reference type is not.

Kirill V. Lyadvinsky
- 97,037
- 24
- 136
- 212
4
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
- 51,293
- 14
- 84
- 114
1
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
- 26,407
- 13
- 68
- 88
1
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
- 3,451
- 2
- 23
- 30
-
1Keep in mind that ordering based on pointers is non-deterministic and likely to change with each invocation of the program. – Rob K Nov 25 '09 at 15:16
-
1Not to mention that keys are compared for equality, and so this is comparing the pointer address values when doing a lookup, and not comparison of the pointer-to value. Specifically, in this example if there were another int e = 2, and you looked up M[&e], you would not get what you might think you are looking for. – mmocny Oct 23 '10 at 05:29