Pairs in map

Hello guys,

Today I was solving this problem: CodeChef: Practical coding for everyone
and I thought of doing it using maps with string as key and value in the map as pair ( pair consists of the number of occurrences of the string with bool 0 and bool 1)

And every time I encounter a string , if it is already in the map then I want to increase the number in the pair by 1 if it is not there I will insert the key and value pair in the map

I implemented this and here is my code :

It will be good if someone tells me how to access the first and the second element of pairs in map

@anon95832944 @ssjgz @sarthakmanna

Thanks a lot!
:slight_smile:

Just change:

if(b == 0) it.second.first++;
                else it.second.second++;

to

if(b == 0) it->second.first++;
                else it->second.second++;

Edit:

Or even better, replace the body of the for loop with:

            cin >> s >> b;
            if (b == 0)
            {
                m[s].first++;
            }
            else
            {
                m[s].second++;
            }
4 Likes

What if key s is not in the map initially ?

What’s the difference between using a dot and -> ?

If you use ., you are trying to access the member named “first” (or “second”) of the iterator object, which doesn’t exist.

If you use -> then you are dereferencing the iterator (to obtain a reference to the object the iterator is referring to) and then trying to access the member named “first”/"second" of that referred object, which does exist.

In other words, by convention, it->blah behaves like (*it).blah, as would be the case if you were dealing with pointers (also by convention, iterators are designed to look/ behave like pointers).

3 Likes

@ssjgz
I got AC , but i wanted to know how this works if the key is not in the map initially

My code :

In the 29th line I am still using x.second.second and it is not giving an error there
Why ?

See the documentation for std::map::operator[] here.

2 Likes

On line 29, the variable x is not an iterator: it is an object of type pair<string, pair<ll, ll>>.

2 Likes

Oh ok
Thanks a lot !! @ssjgz :slight_smile:

1 Like