C++ STL에서 map과 multimap은 기본적으로 요소를 오름차순으로 저장합니다. 하지만 템플릿 인자로 std::greater 함수자를 전달하면 요소를 내림차순으로 저장할 수 있습니다. 이 글에서는 내림차순 map과 multimap의 사용법을 예제 코드와 함께 살펴보겠습니다.
내림차순 map에서 사용되는 주요 함수
m.find() – map에서 키 값 'b'를 가진 요소를 찾으면 해당 위치의 반복자(iterator)를 반환하고, 찾지 못하면 end() 반복자를 반환합니다.
m.erase() – map에서 지정한 키 값을 제거합니다.
m.equal_range() – 반복자 쌍(pair)을 반환합니다. 이 쌍은 해당 키와 동일한 키를 가진 컨테이너 내 모든 요소를 포함하는 범위의 경계를 나타냅니다.
m.insert() – map 컨테이너에 요소를 삽입합니다.
m.size() – map 컨테이너에 저장된 요소의 개수를 반환합니다.
m.count() – map에서 키 값 'a' 또는 'f'와 일치하는 요소의 개수를 반환합니다.
예제 코드
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main () {
// greater<char>를 사용해 내림차순으로 정렬
map<char, int, greater<char>> m;
map<char, int>::iterator it;
m.insert(pair<char, int>('a', 10));
m.insert(pair<char, int>('b', 20));
m.insert(pair<char, int>('c', 30));
m.insert(pair<char, int>('d', 40));
cout << "Size of the map: " << m.size() << endl;
cout << "map contains:\n";
for (it = m.begin(); it != m.end(); ++it)
cout << (*it).first << " => " << (*it).second << '\n';
for (char c = 'a'; c <= 'd'; c++) {
cout << "There are " << m.count(c) << " element(s) with key " << c << ":";
map<char, int>::iterator it;
for (it = m.equal_range(c).first; it != m.equal_range(c).second; ++it)
cout << ' ' << (*it).second;
cout << endl;
}
if (m.count('a'))
cout << "The key a is present\n";
else
cout << "The key a is not present\n";
if (m.count('f'))
cout << "The key f is present\n";
else
cout << "The key f is not present\n";
it = m.find('b');
m.erase(it);
cout << "Size of the map: " << m.size() << endl;
cout << "map contains:\n";
for (it = m.begin(); it != m.end(); ++it)
cout << (*it).first << " => " << (*it).second << '\n';
return 0;
}
실행 결과
Size of the map: 4 map contains: d => 40 c => 30 b => 20 a => 10 There are 1 element(s) with key a: 10 There are 1 element(s) with key b: 20 There are 1 element(s) with key c: 30 There are 1 element(s) with key d: 40 The key a is present The key f is not present Size of the map: 3 map contains: d => 40 c => 30 a => 10
출력 결과를 보면 요소들이 키를 기준으로 d, c, b, a 순서, 즉 내림차순으로 정렬되어 있는 것을 확인할 수 있습니다.
내림차순 multimap
multimap도 map과 동일한 방식으로 greater 함수자를 사용해 내림차순으로 정렬할 수 있습니다. multimap은 하나의 키에 여러 값을 저장할 수 있다는 점이 map과 다릅니다.
사용되는 주요 함수
mm.find() – multimap에서 키 값 'b'를 가진 요소를 찾으면 해당 위치의 반복자를 반환하고, 찾지 못하면 end() 반복자를 반환합니다.
mm.erase() – multimap에서 지정한 키 값을 제거합니다.
mm.equal_range() – 반복자 쌍을 반환합니다. 이 쌍은 해당 키와 동일한 키를 가진 컨테이너 내 모든 요소를 포함하는 범위의 경계를 나타냅니다.
mm.insert() – multimap 컨테이너에 요소를 삽입합니다.
mm.size() – multimap 컨테이너에 저장된 요소의 개수를 반환합니다.
예제 코드
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main () {
// greater<char>를 사용해 내림차순으로 정렬
multimap<char, int, greater<char>> mm;
multimap<char, int>::iterator it;
mm.insert(pair<char, int>('a', 10));
mm.insert(pair<char, int>('b', 20));
mm.insert(pair<char, int>('a', 30));
mm.insert(pair<char, int>('b', 40));
cout << "Size of the multimap: " << mm.size() << endl;
cout << "multimap contains:\n";
for (it = mm.begin(); it != mm.end(); ++it)
cout << (*it).first << " => " << (*it).second << '\n';
for (char c = 'a'; c <= 'd'; c++) {
cout << "There are " << mm.count(c) << " elements with key " << c << ":";
map<char, int>::iterator it;
for (it = mm.equal_range(c).first; it != mm.equal_range(c).second; ++it)
cout << ' ' << (*it).second;
cout << endl;
}
if (mm.count('a'))
cout << "The key a is present\n";
else
cout << "The key a is not present\n";
if (mm.count('f'))
cout << "The key f is present\n";
else
cout << "The key f is not present\n";
it = mm.find('b');
mm.erase(it);
cout << "Size of the multimap: " << mm.size() << endl;
cout << "multimap contains:\n";
for (it = mm.begin(); it != mm.end(); ++it)
cout << (*it).first << " => " << (*it).second << '\n';
return 0;
}
실행 결과
Size of the multimap: 4 multimap contains: b => 20 b => 40 a => 10 a => 30 There are 2 elements with key a: 10 30 There are 2 elements with key b: 20 40 There are 0 elements with key c: There are 0 elements with key d: The key a is present The key f is not present Size of the multimap: 3 multimap contains: b => 40 a => 10 a => 30
정리
map과 multimap은 선언 시 세 번째 템플릿 인자로 비교 기준을 지정할 수 있습니다. 기본값인 std::less 대신 std::greater를 전달하면 컨테이너가 키를 기준으로 내림차순으로 자동 정렬됩니다. 또한 multimap은 동일한 키를 여러 개 허용하므로, equal_range()와 count()를 활용하면 같은 키를 가진 모든 요소를 손쉽게 탐색할 수 있습니다.