STL 에서 map 는 값 (value) 에 따라 정렬 합 니 다.
// : ,
#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);
}
글 의 일부 내용 은 인터넷 에서 참고 하여 작가 에 게 감사 드 립 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
두 가지 전체 배열 (중복수와 무중복수) 의 귀속 실현1. 중복수가 없습니다. 예: abc, 출력: abc\acb\bac\bca\cab\cba. 분석: 순서는 매번 알파벳을 첫 번째 문자로 취하고 뒤의 하위 문자열은 이 과정을 반복하며 전형적인 귀착이다. 2. 중복수가...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.