How to use the c++ map

Asked 2 years ago, Updated 2 years ago, 30 views

When solving AtCoder problem, I have a question about the following solution using map.

Question details

I don't know what pair map<int,int> is connected to. I think mp.first is 2,3,5,7 in input example 3, but am I correct in understanding that mp.second is just an empty box at first?
Also,

2 → Divide by 2, so divide by 1 → 1 → Return 0 because you don't have it yet
3 → I don't have it yet, so I'll return 1
5 → I don't have it yet, so I'll return 2
7→I don't have it yet, so I'll return 3

I thought that the total of 0, 1, 2, and 3 would be the answer, but I am not sure what mp[num]=1 is doing.Thank you for your cooperation.

Current state code

#include<bits/stdc++.h>
using namespace std;

int main() {
    int N;
    cin>>N;
    map<int,int>mp;
    for(inti=0;i<N;++i){
        int num;
        cin>>num;
        while(num%2==0){
            num/=2;
        }
        mp[num] = 1;
    }
    cout<<mp.size()<endl;
    return 0;
}

c++

2022-09-30 14:36

2 Answers

The behavior is correct as others have said, but in this case, the value corresponding to the key is always 1 and there is no point in saving it.In such cases, you should use std::set, where std::set<T> represents a set of (non-overlapping) values of type T.If you insert a value that has already been inserted again, nothing will happen.

For this code, you can rewrite it by set<int> instead of map<int,int> and mp.insert(num) instead of mp[num]=1.


2022-09-30 14:36

This is an example of std::map mp being used as a set. Any value of mp[num] is acceptable, but mp is substituted 1 to express that num is registered in mp.

This question asks how many series of N integers can be divided into when all of the series x, 2x, 4x, 8x, 16x, ... are identified.You can tell which series an integer is in by dividing it by two (which eventually reaches the first number of the series).By treating the first number of a series as a representative of that series, it is easier to count the number of series on the program.

All you have to do is count how many kinds of lines there were.This program uses std::map for this purpose.In other words, after converting each integer to a representative, if num is mp[num]=1, a new definition is added as mp[num]=1 if mp[num] /1 is already defined, nothing will change.After doing this for all integers, check mp.size() to find out the number defined in mp, or the number of series types.

I'll answer your questions now.

Am I correct in understanding that mp.second is just an empty box at first?

No, it doesn't fit very well. The box itself doesn't exist until I replace it. (Also, mp.second() is not defined for std::map, although I can understand...)


2022-09-30 14:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.