example)
std::map<std::string, int> myMap = {
{ “yeongmi”, 4 },
{ “xi”, 3 },
//{ “yeongmi”, 5 }, // => error (use std::multimap instead)
};
constructor
std::map<T1, T2> myMap; // empty map
std::map<T1, T2> myMap(startIt, endIt); // complicated
std::vector<std::pair<T1, T2>> sourceVec = { { “yeongmi”, 4 }, { “xi”, 3 } };
std::map<T1, T2> myMap(sourceVec.begin(), sourceVec.end());
insert : insert / operator[]
std::pair<std::string, int> newPair{“fan”, 7};
myMap.insert(newPair);
myMap[“fan”] = 7; // “fan”이 없을 때 바로 가능
myMap[“yeongmi”] = 5; // update
erase
myMap[“fan”] = 7; // 예시를 위해 먼저 넣음
auto fanIt = myMap.find(“fan”);
myMap.erase(fanIt); // iterator를 넣어줘야 함
find => 주로 그냥 있는지 확인할 때만 사용
std::map<std::string, int>::iterator it = myMap.find(“yeongmi”); // 번거로우니 그냥 auto it = ~~~;
cout << *it << endl; // 4 // iterator의 값을 읽을 때는 * (dereference)
auto it2 = myMap.find(“meghan”);
it2 == myMap.end(); // true
if (myMap.find(“yeongmi”) != myMap.end()) // 있다는 걸 먼저 확인한 후에 출력
{
cout << myMap[“yeongmi”] << endl;
}
access : at / operator[]
cout << myMap[“yeongmi”] << endl; // 4
cout << myMap.at(“yeongmi”) << endl; // 4
count
myMap.count(“fan”); // 0
myMap.count(“yeongmi”); // 1
if (myMap.count(“yeongmi”) == 1) // 위 find에서의 예시와 같은 로직
{
cout << myMap[“yeongmi”] << endl;
}
iterate (한 바퀴 돌기) => iterator 사용
중요) 이 iterator가 가리키는 애도 pair
for (auto it = myMap.begin(); it != myMap.end(); ++it)
{
cout << (*it).first << endl; // print key
cout << it->first << endl; // same as above
cout << (*it).second << endl; // print value
cout << it->second << endl; // same as above
}
for (auto aPair : myMap) // aPair는 pair (iterator 아님)
{
cout << aPair.first << endl;
cout << aPair.second << endl;
}