您的位置:首页 > 职场人生

面试题----统计水果出现次数最多的前三名(map的运用)

2016-11-15 21:14 260 查看
题目描述:某公司为了统计员工最喜爱水果的前三名,发了一份调查问卷,让员工填上自己喜爱的水果名,然后在统计。

思路:在解题的过程中运用2次vector和一次map,第一个vector的目的,是为了把调查问卷的信息保存到容器中(即把水果的信息保存到vector中),map(底层为红黑树)的作用是为统计出一个水果名对应的数量,第二个vector的作用是为了排序,使水果数量从大到小排列,你肯定有疑惑,为什么不使用map排序,因为要排序我调用了STL中算法中的sort()函数,

void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );

sort()函数使用的条件是last和first能相减,而map底层为红黑树,不是连续的内存,所以map的迭代器不支持operator-(),因为vector是一段连续的空间,它支持operator-()。

代码:

#include<iostream>
using namespace std;
#include<cstdlib>
#include<set>
#include<map>
#include<vector>
#include<string>
#include<algorithm>

//统计水果出现次数最多的前三个
void CountTopK(vector<string>& v)
{
map<string,int> countMap;
for(size_t i=0;i<v.size();++i)
{
// 第一种方法
// find()遍历了一遍,insert()又重复遍历了一遍
// map<string,int>::iterator ret=countMap.find(v[i]);
// if(ret!=countMap.end()) //找到
// {
// ret->second ++;
// }
// else //没找到
// countMap.insert(pair<string,int>(v[i],1));

// 第二种方法
//pair<map<string,int>::iterator ,bool> ret=countMap.insert(pair<string,int>(v[i],1));
//if(ret.second ==false) //没插入成功,说明已有
// ret.first ->second ++;

// 第三种方法
countMap[v[i]]++;
}

//只能统计出数量最多的一个
/*map<string,int>::iterator countit=countMap.begin ();
map<string,int>::iterator max=countMap.begin ();
while(countit!=countMap.end())
{
if(countit->second >max->second )
max=countit;
++countit;
}*/

//为了统计出排在前三位置的水果

//第一种解法:把map的迭代器push到vector中,然后调用算法中的sort方法
//vector<map<string,int>::iterator > vinfos; //因为迭代器为4个字节,减少了内存
//map<string,int>::iterator countit=countMap.begin ();
//while(countit!=countMap.end())
//{
// vinfos.push_back (countit);
// countit++;
//}
//仿函数
//struct Compare
//{
// bool operator()(map<string,int>::iterator& l,map<string,int>::iterator& r)
// {
// return l->second > r->second;
// }
//};
//sort(vinfos.begin(),vinfos.end(),Compare()); //从大到小排列

//第二种解法:把pair结构插入到vector中
vector<pair<string,int>> vinfos(countMap.begin (),countMap.end());
//countMap.begin ()的类型为迭代器,解引用后的类型是pair结构
//仿函数
struct Compare
{
bool operator()(pair<string,int>& l,pair<string,int>& r)
{
return l.second > r.second;
}
};

sort(vinfos.begin(),vinfos.end(),Compare()); //从大到小排列

}
int main()
{
vector<string> v;

v.push_back ("苹果");
v.push_back ("苹果");
v.push_back ("香蕉");
v.push_back ("苹果");
v.push_back ("苹果");
v.push_back ("梨");
v.push_back ("梨");
v.push_back ("苹果");
v.push_back ("苹果");
v.push_back ("苹果");
v.push_back ("苹果");
v.push_back ("梨");

//给it指向的位置插入“西瓜”,其他的依次向后拷贝,size+1
/*vector<string>::iterator it=v.begin();
it++;
v.insert(it,"西瓜");*/

CountTopK(v);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试题 map vector
相关文章推荐