Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating map values in c++

Tags:

c++

dictionary

Newb question here: how can I have the value stored in Maptest[2] update along with the variable? I thought you could do it with pointers, but this doesn't work:

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...

What am I doing wrong?

like image 704
Jephron Avatar asked Apr 24 '26 18:04

Jephron


1 Answers

You need the address of x. Your current code is attempting to dereference an integer.

MapTest[2] = &x;

You then need to dereference what MapTest[2] returns.

cout << *MapTest[2]<<endl;
like image 98
chrisaycock Avatar answered Apr 27 '26 07:04

chrisaycock