2016-10-12 4 views
0

私はstd :: mapでオペレータ[]の使用が無効になるのはなぜですか?

struct Node{ 
    Node(){}; 
    int data; 
}; 

私はそれがマップ内にある場合のノードへの参照を返す、または作成するために[]演算子を使用したいが、次のようにノードがあるタイプ

std::map<int, Node> G; 

で地図を持っていると仮定新しいものでなければ参照を返します。これは、ドキュメントが言うの私の理解です:

If k matches the key of an element in the container, the function returns a reference to its mapped value.

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

は、しかし、次のコードは、エラーがスローされます(G ++ 5、STD = GNU ++ 11):全てにおいて

error: cannot convert ‘std::map::mapped_type {aka Node}’ to ‘Node*’ in assignment u_ptr = G[3];

Node* u_ptr; 
u_ptr = G[3]; 

私が見た例は、G[k]がlhsに表示されます。 G[k]はrhsで許可されていませんか?そうでない場合、なぜですか?

+1

あなたのコースブックで*ポインタ*を参照してください。 – krzaq

+0

あなたは 'Node'へのポインタに割り当てますが、マップには' Node'sが含まれています。これは 'Node aとは何の違いもありません。ノード* b = a; '。 – molbdnilo

+0

あなたは 'u_ptr = &G[3];' – Jarod42

答えて

5

std::map<Key, T>::operator[]は、T&のリファレンスを返します。この場合

TNodeので、 G[3]あなたはその後、 Node*ポインタに代入しようとしている Node&参照を返します。そのため、コンパイルエラーが発生しています。

ので、することができます以下のいずれかの基準に

  1. 変更u_ptr

    Node& u_ptr = G[3]; 
    
  2. ポインタへの参照を変換するために&アドレス演算子を使用します。

    Node* u_ptr; 
    u_ptr = &G[3]; 
    
+0

'auto&u_ptr = G [3];' – RyanP

+0

ああ、非常に愚かな間違い...私は "ポインタ"の同義語として "リファレンス"を読んでいる。 – RJTK

+1

@RJTK:コンパイルされたマシンコードでは、参照とポインタは通常同じコードを生成します。しかし意味的に言えば、それらは言語の異なるタイプとして扱われます。 –

関連する問題