一个引用类型能否被用作STL map的键类型?

21

我能否构造一个键类型为引用类型,例如Foo &std::map?如果不能,原因是什么?


1
+1 这是一个很好的问题,许多人害怕提出。 - laura
3
虽然没有直接提到,但是 boost::reference_wrapper<Foo> 应该可以工作。它具有隐式转换为 Foo& 的功能。 - MSalters
4个回答

16
根据C++标准23.1.2/7,key_type应该是可赋值的,但引用类型则不能。

4
不行,因为std::map中的许多函数需要引用keytype,而在C++中引用引用是非法的。

1

使用指针作为std::map的键类型是完全合法的

#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;
}

初始化的引用不能作为键:

#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&

'


1
请记住,基于指针的排序是不确定性的,并且很可能会在每次调用程序时发生变化。 - Rob K
1
更不用说键的比较是为了相等性,因此在查找时比较的是指针地址值,而不是指针值的比较。具体来说,在这个例子中,如果有另一个int e = 2,并且您查找M[&e],您将得到与您想要查找的内容不同的结果。 - mmocny

1
考虑 operator[](const key_type & key)。 如果key_typeFoo &,那么const key_type &是什么? 问题在于它不起作用。您无法构造一个键类型为引用类型的std :: map。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接