Laurent
Laurent

Reputation: 6205

Calling a method on a value stored in a std::map

In the following code:

class Abc {
    int x;
    void clear() { x=0; }
}


map<string, Abc> mymap;
Abc abc1;
abc1.x = 12;
mymap[1] = abc1;

map<string, Abc>::iterator it = mymap.begin();
it->second.clear();

map<string, Abc>::iterator it2 = mymap.begin();
cout << it2->second.x; // what will this display?

Supposing I have no errors (map is not empty, etc.), will the call to clear modify the element stored in the map, or a copy?

I know that if I stored Abc* pointers in the map, there would be no problem, it would print 0, but I can't figure if second returns a value or a reference, and if I'm clearing the value that's in the map or a copy of it.

Upvotes: 0

Views: 775

Answers (4)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361472

map<string, Abc> mymap;
Abc abc1;
abc1.x = 12;
mymap[1] = abc1;

Compilation error :

Because the key type is string, but you passing 1 to mymap as key.

cout << it2->second.x; // what will this display?

It will display the value of x : 0

This is equivalent to this:

Abc a;
a.x = 12;
a.clear();
cout << a.x ; //prints 0, because a.clear() made it 0!

Upvotes: 1

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76818

Why don't you just try? You can write a copy constructor for Abc that prints out a message when the object is copied:

class Abc {
public:
    Abc(const Abc & other) 
     : x(other.x)
    {
        std::cout << "copying" << std::endl;
    }
    void clear() { x=0; }
private:
    int x;
}

Using this, you can find out if your object is getting copied. You should do things like that to learn how things work.

Upvotes: 0

Nikko
Nikko

Reputation: 4252

It will modify the element in the map, .second is not a function it's a member of a std::pair structure

Upvotes: 0

Erik
Erik

Reputation: 91270

second is a reference - you're modifying the element stored in the map. Or, to be specific, *it is a reference to the std::pair stored in the map, second is the actual element.

Upvotes: 1

Related Questions