728x90
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include<map>
using namespace std;
int main(void)
{
multimap <string, string> mm;
multimap <string, string> ::iterator mmiter;
vector<string>kind_name1;
vector<string>kind_name2;
vector<string>kind_name3;
vector<vector<string>> clothes;
kind_name1.push_back("yellowhat");
kind_name1.push_back("headgear");
kind_name2.push_back("bluesunglasses");
kind_name2.push_back("eyewear");
kind_name3.push_back("green_turban");
kind_name3.push_back("headgear");
clothes.push_back(kind_name1);
clothes.push_back(kind_name2);
clothes.push_back(kind_name3);
for (int i = 0; i < clothes.size(); i++)
{
for (int j = 0; j < clothes[i].size()-1; j++)
{
string name = clothes[i][j];
string kind = clothes[i][clothes[0].size() - 1];
pair<string, string> p1 = make_pair(kind, name);
mm.insert(p1);
}
}
for (auto i = mm.begin(); i != mm.end(); i++)
{
cout << i->first << "," << i->second << endl;
}
for (auto i = mm.begin(); i != mm.end(); i++)
{
int k = mm.count(i->first);
cout << k;
}
//중복 키 값이 존재하는 headgear 의 인자 출력.
for (mmiter = mm.equal_range("headgear").first; mmiter != mm.equal_range("headgear").second; mmiter++) {
cout << "[" << mmiter->first << ", " << mmiter->second << "] ";
}
cout << endl;
return 0;
}
출력결과
eyewear,bluesunglasses
headgear,yellowhat
headgear,green_turban
122[headgear, yellowhat] [headgear, green_turban]
설명
- multimap은 map과 거의 동일하지만 key값이 중복 가능하다.
- Ordered : Key, Value 값이 삽입될때 정렬이 되면서 삽입된다. (항상 정렬되어있는 상태)
- Map : 각각의 Key는 하나의 Value 에 mapping된다. (pair 객체를 이용하여 key, value를 묶습니다.)
- multimap은 중복 key를 허용한다.
for (auto i = mm.begin(); i != mm.end(); i++)
{
cout << i->first << "," << i->second << endl;
}
그러므로 출력시에는 <first, second>임을 명심해서
반복자->first으로 키에 접근,
반복자->second로 value에 접근해야한다.
map과 달리 같은 Key에 여러 Value를 담을 수 있는 multimap이기에
multimap의 처음과 끝까지 달리는 반복자를 통해
exmultimap.count(i->first)를 검토해주면
각 Key에 몇개의 value가 담겨있는지 확인해볼 수 있다.
for (auto i = mm.begin(); i != mm.end(); i++)
{
int k = mm.count(i->first);
cout << k;
}
참고로 반복자를 통한 접근은 아래 두 코드 방식에서 동일하게 작용한다.
두 방식 모두 익숙해지는 것이 좋겠다.
for (auto i = mm.begin(); i != mm.end(); i++)
{
cout << i->first << ", " << i->second << endl;
}
multimap<string, string>::iterator iter;
for (iter = mm.begin(); iter != mm.end(); iter++) {
cout << iter->first << ", " << iter->second << endl;
}
728x90
'C++ > c++' 카테고리의 다른 글
[STL] map (0) | 2022.01.15 |
---|---|
[STL] Vector내 최대값, 최소값과 그 인덱스 알아내기 (0) | 2022.01.11 |
[STL] unordered_map과 make_pair 같이 쓰기 (0) | 2022.01.04 |
[STL] 이중 Vector : 예시 vector<vector<string>>, 코드첨부 (0) | 2022.01.04 |
[STL] multimap의 탐색 방법 (0) | 2022.01.04 |