简体   繁体   中英

Updating map values in c++

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?

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;

Try this instead:

MapTest[2] = &x; 

You want the address of x to store in the int* . Not the dereference of x, which would be what ever is at the memory location 0x7, which is not going to be valid.

There are at least 2 problems here:

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

Now you have a new problem. x has automatic lifetime, it will be destroyed at the end of its surrounding scope. You need to allocate it from the free store (aka the heap).

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

Now you have to remember to delete every element in the map before it goes out of scope or you will leak memory.

It is smarter to store values in a map , or if you really need to store pointers to store a suitable smart pointer ( shared_ptr or unique_ptr ).

For the printing:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM