C++/C++ Common
map
doublerabbits
2022. 8. 6. 19:36
map 은 Key 값을 기준으로 중복 데이터가 불가
선언
map<string, int> map1;
데이터 추가
map1.insert({ "1st", 111 });
map1.insert({ "2nd", 222 });
map1.insert({ "3rd", 333 });
map1.insert({ "4th", 444 });
map1.insert({ "5th", 555 });
데이터 변경
map1["1st"] = 1;
map1["Last"] = 999;
데이터 찾기 및 삭제
iter = map1.find("4th");
if (iter == map1.end())
{
printf("4th not found \n");
}
else
{
cout << "4th found = " << iter->first << " : " << iter->second << "\n";
}
map1.erase(iter);
키 기반 데이터 삭제
map1.erase("5th");
전체 데이터 삭제
map1.clear();
맵이 비어있는지 확인
map1.empty()
데이터 순환
for (iter = map1.begin(); iter != map1.end(); ++iter)
{
cout << iter->first << " : " << iter->second << "\n";
}
printf("map1 size(%d) = %zd \n\n", map1.empty(), map1.size());
예제
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, int> map1;
map<string, int>::iterator iter;
printf("map1 size(%d) = %zd \n\n", map1.empty(), map1.size());
map1.insert({ "1st", 111 });
map1.insert({ "2nd", 222 });
map1.insert({ "3rd", 333 });
map1.insert({ "4th", 444 });
map1.insert({ "5th", 555 });
printf("map1 size(%d) = %zd \n\n", map1.empty(), map1.size());
for (iter = map1.begin(); iter != map1.end(); ++iter)
{
cout << iter->first << " : " << iter->second << "\n";
}
printf("map1 size(%d) = %zd \n\n", map1.empty(), map1.size());
iter = map1.find("4th");
if (iter == map1.end())
{
printf("4th not found \n");
}
else
{
cout << "4th found = " << iter->first << " : " << iter->second << "\n";
}
map1.erase(iter);
iter = map1.find("4th");
if (iter == map1.end())
{
printf("4th not found \n");
}
else
{
cout << "4th found = " << iter->first << " : " << iter->second << "\n";
}
map1.erase("5th");
map1["1st"] = 1;
map1["Last"] = 999;
for (auto iter2 : map1)
{
cout << iter2.first << " : " << iter2.second << "\n";
}
printf("map1 size(%d) = %zd \n\n", map1.empty(), map1.size());
map1.clear();
printf("map1 size(%d) = %zd \n\n", map1.empty(), map1.size());
int userInput;
cin >> userInput;
return 0;
}
STL
STL(Standard Template Library) 템플릿을 사용하여 자료형에 관계없이 범용적인 프로그래밍을 가능하게 하는 라이브러리 STL 구성 요소 Container 기본 자료형 또는 사용자 정의 자료형을 담는 자료 구조
doublerabbits.tistory.com