#include <map>
int main()
{
// 선언
std::map<std::string, int> map;
std::map<Score, int> map;
std::map<Score, int> mapClone(map); // 복사 생성자
// pair
std::pair<std::string, int> map("Coco", 10);
// 삽입
map.insert(std:pair<std::string, int>("Mocha", 100));
map["Coco"] = 10; // 없으면 삽입, 있으면 수정
// 넣은 순서와 상관없이 key값으로 정렬된다.
// 삽입될때 key값이 class라서 트리에 넣기위해 비교를 못하면, 비교 연산자 필요
// 1. 연산자 정의 (*선호)
bool MyClass::operator<(const MyClass& otherClass) const
{
return name > other.name;
}
// 2. Comparer 정의 (1방법을 못 쓸경우)
struct MyComparer
{
bool operator()(const MyClass& left, const MyClass& right) const
{
return (left.getName() < right.getName());
}
}
std::map<MyClass, int, MyComparer> myMap;
// 읽기
map["Coco"];
// Key 값의 Value 반환.
주의!! 넣은적이 없어도 임의의 값이 나온다.
// 찾기
std::map<std::string, int>::iterator it = map.find("Mocha");
if (it != map.end())
{ // 찾음
cout << it->first; // key 출력
cout << it->second; // value 출력
}
else
{ // 못찾음
cout << "Not found" << endl;
}
map.swap(otherMap); // 교환
map.clear(); // 모드 제거
map.erase(key); // key로 제거 (*선호)
map.erase(iterator); // iterator로 제거
}
탐색 속도가 빠름
자동 정렬됨
hashmap이 아님, O(1)이 아님
C++11에 해결책이 있음