map 은 dictonary 같은 자료형으로 key value 쌍을 이룬다.
c++ 에서 map 은 항상 key 기준으로 오름차순을 정령된다.
p.s) 내림차순 정렬을 위해서는 map<int,int,greater> mp ; 와 같이 정의해 주면 되다.
1. map 선언 데이터 추가 방법
// insert
mx1.insert({ "abp",1 });
mx1.insert({ "bbb",2 });
mx1["ccc"] = 3;
for (auto it = mx1.begin(); it != mx1.end(); it++)
{
cout << it->first<< ','<< it->second << endl;
}
iterator 의 first 와 second 를 통해서 key, value 에 접근할 수있다.
2. map.find
if (mx1.find("abp") != mx1.end())
{
cout << "find" << endl;
}
찾으면 찾은 iterator return 못찾으면 end() 값 반환
3. erase
특정 iterator 로 삭제 or key 값으로 삭제
mx1.insert({ "abp",1 });
mx1.insert({ "bbb",2 });
mx1["ccc"] = 3;
for (auto it = mx1.begin(); it != mx1.end(); it++)
{
cout << it->first<< ','<< it->second << endl;
}
mx1.erase(mx1.find("abp"));
mx1.erase("bbb");
for (auto it = mx1.begin(); it != mx1.end(); it++)
{
cout << it->first << ',' << it->second << endl;
}
ps) m.erase(m.begin(), m.end()); 와 같이 iterator 범위로 삭제 또한 가능하다
map key 가 존재 하지 않을때
#include <string>
#include <vector>
#include<algorithm>
#include <map>
#include <iostream>
using namespace std;
int main()
{
map<string, int> mp;
mp["aaa"] = 1;
cout << mp["aaa"];
mp["aaad"];
for (auto it = mp.begin(); it != mp.end(); it++)
{
cout << it->first << ',' << it->second << endl;
}
if (mp.find("ccc") == mp.end())
{
cout << "키값이 존재 하지 않습니다.";
}
return 0;
}
[] 연산자로 접근한다면 map 에서는 key value 쌍을 만들어 준다.
때문에 key 값이 존재하는지 알기 위해서는 find 함수를 사용하는것을 추천한다.
rbegin(), rend() map 거꾸러 순회할때 사용
map<string, int> mp;
mp["aaa"] = 1;
mp["aaad"];
for (auto it = mp.rbegin(); it != mp.rend(); it++)
{
cout << it->first << ',' << it->second << endl;
}
댓글