2009-11-25 7 views
18

std::mapを構成できますか?キータイプは参照タイプです。 Foo &もしそうでなければ、どうしてですか?STLマップのキータイプとして参照タイプを使用できます

+1

+1が、これは良い質問であります多くは尋ねることを恐れている。 – laura

+3

直接ではありませんが、 'boost :: reference_wrapper 'が動作するはずです。 'Foo&'への暗黙的な変換を持っています – MSalters

答えて

14

C++標準に従って23.1.2/7 key_typeに割り当てる必要があります。参照型はありません。 std ::マップのキー型として

4

いいえ、std :: mapの関数の多くはkeytypeへの参照をとり、参照の参照はC++では不正です。

/A.B。

1

operator[](const key_type & key)とします。 key_typeFoo &の場合、const key_type &とは何ですか? 問題は機能しないことです。キーの型が参照型の場合は、std :: mapを構築することはできません。

1

ポインタは

#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

ポインタに基づく順序付けは非決定論的で、プログラムの呼び出しごとに変わる可能性があることに留意してください。 –

+1

キーが等しいかどうか比較されることは言うまでもありません。したがって、ポインタの値を比較するのではなく、ルックアップを行うときにポインタのアドレス値を比較しています。具体的には、この例では、別のint e = 2があり、M [&e]を参照すると、あなたが探していると思われるものが得られません。 – mmocny

関連する問題