STL 에서 map 는 값 (value) 에 따라 정렬 합 니 다.

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);  
}  

글 의 일부 내용 은 인터넷 에서 참고 하여 작가 에 게 감사 드 립 니 다.

좋은 웹페이지 즐겨찾기