[STL] map
#include <map>
C++
복사
map?
•
자료를 저장할때 내부에서 자동으로 정렬
•
map은 key를 기준으로 정렬하며 오름차순으로 정렬한다
•
내림차순으로 정렬하고 싶다면?
map<int, int, greater> map1;
C++
복사
map 선언
// map <key type, value type>
map<string, int> m;
C++
복사
map에 찾고자 하는 데이터가 있는지 확인하기 (search)
•
map에서 데이터를 찾을 때는 iterator을 사용
•
데이터를 끝까지 찾지 못했을 경우, iterator는 map.end()를 반환
if (m.find("Alice") != m.end()) {
cout << "find" << endl;
}
else {
cout << "not find" << endl;
}
C++
복사
map에 데이터 삽입
•
map은 중복을 허용하지 않는다
•
insert를 수행할 때, key가 중복되면 insert가 수행되지 않는다
•
중복되면 그것은 key의 역할을 제대로 하지 않는다
m.insert({"Cam", 300});
C++
복사
반복문 데이터 접근 (first, second)
인덱스 기반 반복문 활용한 예제
// 인덱스 기반
for (auto iter = m.begin(); iter != m.end(); iter++) {
cout << iter->first << " " << iter->second << endl;
}
cout << endl;
C++
복사
범위 기반 반복문 활용한 예제
for (auto iter : m) {
cout << iter.first << " " << iter.second << endl;
}
C++
복사
map에서 삭제
특정 위치의 요소 삭제
m.erase(m.begin()+2);
C++
복사
key값을 기준으로 요소 삭제
m.erase("Alice");
C++
복사
map의 모든 요소 삭제
// erase함수로 모든 요소 삭제하기 (map의 begin부터 end까지)
m.erase(m.begin(), m.end());
// clear함수로 모든 요소 삭제하기
m.clear();
C++
복사
예제
#include <iostream>
#include <map>
using namespace std;
map<string, int> m;
int main() {
m.insert({"Alice", 100});
m.insert({"Bob", 200});
if (m.find("Alice") != m.end()) {
cout << "found" << "\n";
}
else {
cout << "Not found" << "\n";
}
// 인덱스 기반
for (auto iter = m.begin(); iter != m.end(); iter++) {
cout << iter->first << " " << iter->second << '\n';
}
cout << '\n';
// 범위 기반
for (auto iter : m) {
cout << iter.first << " " << iter.second << '\n';
}
return 0;
}
C++
복사
예제 2)
vector<int> solution(vector<string> name, vector<int> yearning, vector<vector<string>> photo) {
vector<int> answer;
map<string, int> m;
for (int i = 0; i < name.size(); i++) {
m.insert({name[i], yearning[i]});
}
// for (auto iter = m.begin(); iter != m.end(); iter++) {
// cout << iter->first << ", " << iter->second << '\n';
// }
for (int i = 0; i < photo.size(); i++) {
int sum = 0;
for (int j = 0; j < photo[i].size(); j++) {
if (m.find(photo[i][j]) != m.end()) {
auto it = m.find(photo[i][j]);
sum += it->second;
}
else continue;
}
answer.push_back(sum);
}
return answer;
}
C++
복사