728x90
반복문 데이터 접근 (first, second)
- 인덱스 기반 반복문 활용한 예제
: 인덱스 기반은 iterator을 활용하여 begin()부터 end()까지 찾는다.
//인덱스기반
for (auto iter = m.begin() ; iter ! = m.end(); iter++)
{
cout << iter->first << " " << iter->second << endl;
}
cout << endl;
- 범위 기반 반복문 활용한 예제
for (auto iter : m) {
cout << iter.first << " " << iter.second << endl;
}
map에서 삭제하기
map에서 데이터를 삭제하기 위해 활용할 함수는 erase와 clear
(1)특정 위치의 요소 삭제
m.erase(m.begin()+2);
(2)key값을 기준으로 요소 삭제
m.erase("naver");
(3)map의 모든 요소 삭제
- erase 함수로 모든 요소 삭제 (map의 begin부터 end까지)
m.erase(m.begin(), m.end());
- clear 함수로 모든 요소 삭제하기
m.clear();
map 사용 구문 ( 삽입, 찾기, 반복문 구현 )
#include <iostream>
#include <map>
using namespace std;
map<string, int> mapset;
int main(void) {
mapset.insert({ "naver", 100 });
mapset.insert({ "kakao", 200 });
mapset.insert({ "line", 200 });
if (mapset.find("naver") != mapset.end())
{
cout << "find" << endl;
}
else {
cout << "not find" << endl;
}
//인덱스기반
for (auto iter = mapset.begin() ; iter != mapset.end(); iter++)
{
cout << iter->first << " " << iter->second << endl;
}
cout << endl;
//범위기반
for (auto iter : mapset) {
cout << iter.first << " " << iter.second << endl;
}
return 0;
}
728x90
'C++ > c++' 카테고리의 다른 글
[STL] unique로 vector에서 중복 원소 제거하기 : 선 sort 후 unique! (0) | 2022.01.16 |
---|---|
[STL] map에서 Value를 기준으로 정렬하고 싶을 경우 (0) | 2022.01.15 |
[STL] Vector내 최대값, 최소값과 그 인덱스 알아내기 (0) | 2022.01.11 |
[STL] key 중복가능한 multimap과 make_pair 조합 (0) | 2022.01.05 |
[STL] unordered_map과 make_pair 같이 쓰기 (0) | 2022.01.04 |