2009-11-25 71 views
18

我可以构造密钥类型是引用类型(例如,引用类型)的std::mapFoo &如果不是,为什么不呢?可以使用引用类型作为STL映射中的密钥类型

+1

+1这是一个很好的问题是很多人都不敢问。 – laura 2009-11-25 10:52:46

+3

不是直接的,但'boost :: reference_wrapper '应该可以工作。它有一个隐式转换为'Foo&' – MSalters 2009-11-26 10:11:06

回答

14

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

4

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

/A.B。

1

考虑operator[](const key_type & key)。 如果key_typeFoo &那么什么是const key_type &? 事情是它不起作用。你不能构造一个std :: map,其中键类型是引用类型。

1

指针作为关键类型的std ::地图是完全合法的

#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

请记住,基于指针的排序是非确定性的,并可能随程序的每次调用而改变。 – 2009-11-25 15:16:40

+1

更不用说比较键是否相等,因此这是比较查找时的指针地址值,而不是指针值的比较。具体来说,在这个例子中,如果有另外一个int e = 2,并且你查找了M [&e],你就不会得到你认为你正在寻找的东西。 – mmocny 2010-10-23 05:29:53

相关问题