2011-12-31 69 views
3

Newb question here: 如何將存儲在Maptest [2]中的值與變量一起更新? 我想你可以用指針做到這一點,但是這並不工作:在C++中更新地圖值

map<int, int*> MapTest; //create a map 

    int x = 7; 

    //this part gives an error: 
    //"Indirection requires pointer operand ("int" invalid)" 
    MapTest[2] = *x; 


    cout << MapTest[2]<<endl; //should print out 7... 

    x = 10; 

    cout <<MapTest[2]<<endl; //should print out 10... 

我在做什麼錯?

+3

旁註:該'&'取地址,''是一個引用操作和derefs一個指針。 – birryree 2011-12-31 19:34:18

+1

既然你想要指向x的指針,你應該這樣做,而不是:'MapTest [2] =&x;' – lfxgroove 2011-12-31 19:36:45

+0

代碼在幾個方面是錯誤的。應該是MapTest [2] =&x; '並使用'* MapTest [2]'來訪問值。你是否熟悉指針? – 2011-12-31 19:39:41

回答

4

您需要地址x。您當前的代碼正試圖取消引用整數。

MapTest[2] = &x; 

然後您需要解除引用MapTest[2]返回的內容。

cout << *MapTest[2]<<endl; 
+0

謝謝,這解決了它。 – Jephron 2011-12-31 21:59:29

0

試試這個:

MapTest[2] = &x; 

你想要x的地址在int*存儲。不是x的取消引用,這將永遠是在內存位置0x7,這是不會有效的。

+0

彼得亞歷山大關於印刷東西的說法。 – 2011-12-31 19:35:55

0

至少有2個問題在這裏:

int x = 7; 
*x; // dereferences a pointer and x is not a pointer. 
m[2] = x; // tries to assign an int value to a pointer-to-int value 
// right 
m[2] = &x; // & returns the address of a value 

現在你有一個新的問題。 x具有自動生命週期,將在其周圍範圍的末端銷燬 。您需要從免費商店(a.k.a.堆)分配 。

int* x = new int(7); 
m[2] = x; // works assigns pointer-to-int value to a pointer-to-int value 

現在你要記得delete每個元素在它超出範圍 的map之前或將導致內存泄漏。

這是聰明存儲在map值,或者如果你真的需要 存儲指向存儲合適的智能指針(shared_ptrunique_ptr)。

對於打印:

m[2]; // returns pointer value 
*m[2]; // dereferences said pointer value and gives you the value that is being pointed to