简体   繁体   中英

How do I create a pointer to key/value pair of a map in C++?

I'm trying to explore the different ways of creating pointers. In the following code, I'm trying to create a pointer pointing to a key/value pair of a map in two different ways:

#include <iostream>
#include<map>
using namespace std;

int main(){
    //creating the map & the key/value pair
    map<string,string> mp;
    mp["key"]="value";

    //This gives an error:taking the address of a temporary object?
    map<string,string>* pt = &(mp.begin());


    //This, however, works perfectly fine.
    auto it = mp.begin();

    cout<<it->first<<endl<<it->second;//testing

}

I don't understand why the first attempt spits out an error, and the second one works fine. Can someone please explain?

mp.begin() does not return a pointer, it returns an iterator, which is an object that represents a reference to an entry, but still an object in of itself.

You can convert an iterator into a pointer by using &*iterator , which means "The address of ( & ) the object referred to ( * ) by that iterator".

Next up, map<string,string>* is a pointer to the map itself. If you want a pointer to an entry within the map, you need to use map<string, string>::value_type* .

Putting all that together, what you want is:

map<string, string>::value_type* pt = &*mp.begin();

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