:안녕하세요
:
:제가 프로그래밍중 다음과 같은 문제에 봉착했는데, 제가 기초가 부족
:해서 인지 하루종일 생각해 봐도 통 감이 안옵니다.
:
:배열, 혹은 파일에 다음과 같은 데이타가 있을때,
:
:aaa
:aaa
:bbb
:bbb
:bbb
:ccc
:ccc
:ccc
:ccc
:
:이것을 다음과 같이 정렬합니다.
:
:ccc
:ccc
:ccc
:ccc
:bbb
:bbb
:bbb
:aaa
:aaa
;
:즉 c 가 가장 많으니까, 제일 위로 올라가고 그다음 b a 이런 식으로
:정렬이 되게 하는 겁니다.
:생각날듯 말듯, 생각이 않나는 군요 ㅠㅠ
이런 경우는 트리나 해쉬테이블과 같은 연관 컨테이너(associative container)를 사용하는 방법이
가장 간단하고, 빠르며, 메모리 사용량도 적습니다.
다음은, STL의 연관 컨테이너인 map과, multimap을 사용하는 방법입니다.
//---------------------------------------------------------------------------
#include <iostream>
#pragma hdrstop
#include <iterator>
#include <functional>
#include <string>
#include <map>
#include <vector>
//---------------------------------------------------------------------------
using namespace std;
#pragma argsused
int main(int argc, char* argv[])
{
typedef vector<string> vec_str;
vec_str input_words, output_words;
input_words.push_back("aaa");
input_words.push_back("aaa");
input_words.push_back("bbb");
input_words.push_back("bbb");
input_words.push_back("bbb");
input_words.push_back("ccc");
input_words.push_back("ccc");
input_words.push_back("ccc");
input_words.push_back("ccc");
typedef map<string, int> freq_map; // 여기서는 map 대신에 hash_map을 써도 좋습니다.
freq_map freq;
for (size_t i = 0; i < input_words.size(); ++i)
// freq에 words[i]가 있으면 1만큼 증가,
// 없으면 새로 추가하고 빈도를 1로 세팅.
freq[input_words[i]]++;
typedef multimap<int, string> invert_freq_map;
invert_freq_map invert_freq;
for (freq_map::iterator i = freq.begin(); i != freq.end(); ++i)
invert_freq.insert(make_pair(i->second, i->first));
// 단어와 빈도를 거꾸로 해서 multimap에 저장
for (invert_freq_map::iterator i = invert_freq.begin();
i != invert_freq.end(); ++i)
for (int j = 0; j < i->first; ++j) // 빈도만큼 output_words에 삽입
output_words.push_back(i->second);
copy(output_words.rbegin(), output_words.rend(),
ostream_iterator<string>(cout, "\n")); // output_words를 cout에 출력
return 0;
}
|
map <string, int> mapCumCount;
mapCumCount["aaa"]++;
그다음 소팅.