2009-11-25 68 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

相關問題