An organization held an election to select a leader.The organization consists of N members, each with the most appropriate leader's name.
The leader will be chosen by the person who gets the most votes.Print the name of the person with the most votes.If you have more than one person who gets the most votes, you can print any name.
Inputs are given from standard input in the following format:
N
S1
S2
:
SN
Print the name of the person with the most votes.If there are a plurality of persons with the largest number of votes, any name may be outputted.Put a new line at the end of the output as well.
I have a question about the following answer code using std::map
of the above question.
#include<bits/stdc++.h>
using namespace std;
int main() {
int N, max = 0;
string S,ans;
map<string, int>m;
cin>>N;
for (inti=0;i<N;i++)
{
cin>>S;
m[S]++;
if(max<m[S]){
max = m[S];
an=S;
}
}
cout<ans<<endl;
return 0;
}
I understand what m[S]++
means in the code, but I can't explain exactly.
Input e.g.
4
taro
Jiro Corporation
taro
saburo
As a behavior when it comes to
I understand that m[S]++
means m[S]=m[S]+1
, so could you tell me how it works?Thank you for your cooperation.
std::map
m[s] behavior is
m
already contains the s
element, return the stored value as the left side value.m
If there is no s
element in s
element is constructed by default and returned as a left side valueThe first time m["taro"]
is evaluated, the m["taro"
element is still missing in m
, so the m["taro"]
itself and its value int
are created. The default Construct value for is
.This source code says
m["taro"]++;
, so the value changes to 1
.
The second evaluation of m["jiro"]
does not have this element, so the new initial value is 0
, and ++
changes to 1
.
The third time m["taro"]
is evaluated, it returns a value of m["taro"]
that already exists.The value changes to 2
because it contains 1
.
A behavioral sample of that area. Let's guess what the display will look like before you run it.
#include<map>
# include <iostream>
# include <string>
int main() {
std::map<std::string, int>m;
std::cout<<m.size()<<std::endl;
m["taro" ];
std::cout<<m.size()<<std::endl;
std::cout<<m["taro"]<<std::endl;
++m["jiro"];
std::cout<<m["jiro"]<<std::endl;
}
The competition programming industry-specific #include<bits/stdc++.h>
is not a typical is not a typical job<-a class で"test -"test" task.Global using namespace std;
is also disliked by Pure c++er.Don't think of competition programming as the world's common sense.
679 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
540 Unable to install versioned in Google Colab
543 Understanding How to Configure Google API Key
546 Who developed the "avformat-59.dll" that comes with FFmpeg?
524 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.