首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

一个vector 求其中出现最多次的元素解决办法

2012-04-10 
一个vector 求其中出现最多次的元素如题[解决办法]假设有一个std::vectorT testList建立一个mapstd::ma

一个vector 求其中出现最多次的元素
如题

[解决办法]
假设有一个std::vector<T> testList;
建立一个map
std::map<T, int> keyList; //以元素值作为key,计数作为value
遍历test列表
std::vector<T>::iterater iter;
for(; iter != testList.end(); ++iter)
{
keyList[*iter]++;
}
遍历keyList列表找到value最大的key
std::map<T, int>::iterater iter;
int maxvalue = 0;
int key = -1;
for(; iter != keyList.end(); ++iter)
{
int temp = 0;
temp= iter->second;
if(temp>=maxvalue )
{
key = iter->first;
}
}



热点排行