首页 > 代码库 > 众数问题

众数问题

#include<iostream>
#include<map>
#include<iterator>

using namespace std;
int main()
{

int N;
cin>>N;
while(N--)
{
map<int,int>group;
int Num,value;
cin>>Num;
map<int,int>::iterator it;
for(int i=1;i<=Num;i++)
{
	cin>>value;
	it=group.find(value);
	if(it==group.end())
		group[value]=1;
	else
		it->second+=1;

}
int mode,T_mode=0;
for(it=group.begin();it!=group.end();it++)
{
	if(it->second>T_mode)
	{
		mode=it->first;
		T_mode=it->second;
	}
}

cout<<mode<<" "<<T_mode<<endl;

}

}

因为我不太确定map的初始值是多少所以用find函数做了,后来查了资料发现初始值;

一句话不割,a=map[i],如果map[i]没有值的话,会赋一个初始值给a,如果map是<?,int>则a=0,如果<?,string>则a=""

那就不需要find函数了