firemail
标题:
统计出现次数和对map按value排序
[打印本页]
作者:
jimu
时间:
2016-5-2 12:09
标题:
统计出现次数和对map按value排序
CDR_PILOT stPilotTemp;
CDR_CELL_EX stCellExTemp;
//map<__int64, CDR_CELL_EX> m_mapCellEx;
for( map<string, CDR_CELL>::iterator itor = m_mapCell.begin(); itor != m_mapCell.end(); itor++ )
{
vector<CDR_CELL_EX> vec_CellEx;
for( size_t i = 0; i < itor->second.vec_pilot_other.size() ; i++ )
{
stPilotTemp = itor->second.vec_pilot_other[i];
bool bfind = false;
for (vector<CDR_CELL_EX>::iterator itcellex = vec_CellEx.begin(); itcellex != vec_CellEx.end(); itcellex++ )
{
if ( itcellex->stPilot.NE_SYS_ID == stPilotTemp.NE_SYS_ID )
{
bfind = true;
itcellex->nPilotCount++;
break;
}
}
if (!bfind)
{
stCellExTemp.nPilotCount = 1;
stCellExTemp.stPilot = stPilotTemp;
vec_CellEx.push_back(stCellExTemp);
}
//map<__int64, CDR_CELL_EX>::iterator itfind = m_mapCellEx.find(stPilotTemp.NE_SYS_ID);
//if (itfind == m_mapCellEx.end()) //没有查找到,则增加一条
//{
// m_mapCellEx[stPilotTemp.NE_SYS_ID].nCountValue = 1;
// m_mapCellEx[stPilotTemp.NE_SYS_ID].stPilot = stPilotTemp;
//}
//else
//{
// m_mapCellEx[stPilotTemp.NE_SYS_ID].nCountValue++;
//}
}
上面如果使用map<__int64, CDR_CELL_EX> 把则需要对它的value进行排序
http://www.cnblogs.com/wanpengcoder/archive/2010/10/24/1859682.html
map默认是按照键(key)排序的。很多时候我们需要按值(value)排序,靠map里的
算法当然是不行的,那么可以把它转存到vector中,在对vector按照一定的规则排序即可。
//示例代码:输入单词,统计单词出现次数并按照单词出现次数从多到少排序
#include <cstdlib>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
void sortMapByValue(std::map<std::string, int>& tMap, std::vector<std::pair<std::string, int> >& tVector);
int cmp(const std::pair<std::string, int>& x, const std::pair<std::string, int>& y);
int main()
{
std::map<std::string, int> tMap;
std::string word;
while (std::cin >> word)
{
std::pair<std::map<std::string, int>::iterator, bool> ret = tMap.insert(std::make_pair(word, 1));
if (!ret.second)
++ret.first->second;
}
std::vector<std::pair<std::string,int> > tVector;
sortMapByValue(tMap,tVector);
for(int i=0;i<tVector.size();i++)
{
std::cout<<tVector[i].first<<": "<<tVector[i].second<<std::endl;
}
system("pause");
return 0;
}
int cmp(const std::pair<std::string, int>& x, const std::pair<std::string, int>& y)
{
return x.second > y.second;
}
void sortMapByValue(std::map<std::string, int>& tMap, std::vector<std::pair<std::string, int> >& tVector)
{
for (std::map<std::string, int>::iterator curr = tMap.begin(); curr != tMap.end(); curr++)
{
tVector.push_back(std::make_pair(curr->first, curr->second));
}
std::sort(tVector.begin(), tVector.end(), cmp);
}
复制代码
欢迎光临 firemail (http://firemail.wang:8088/)
Powered by Discuz! X3