spiritedExit0
spiritedExit0

Reputation: 93

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?

Upvotes: 0

Views: 726

Answers (1)

user4442671
user4442671

Reputation:

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();

Upvotes: 4

Related Questions