C++/c++

[STL] unordered_map과 make_pair 같이 쓰기

Rainbow🌈Coder 2022. 1. 4. 21:45
728x90

unordered_map은 hash 기반으로 map tree 기반으로 구현되기 때문에

 

unordered_map의 key들은 정렬되어 있지 않고, map의 key들은 정렬되어있다.

 

탐색방법

  • index로 접근할 수 없고 iterator로 접근
  • 시작 : begin( ), 끝 : end( )
  • key : iter->first, value : iter->second
  • 반복문 사용 시 auto 활용 or pair< key_type, value_type > 사용
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <utility>

using namespace std;

int main(void)
{
	unordered_map<string, string> hs;

	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(name, kind);
			hs.insert(p1);
		}
	}

	for (auto i = hs.begin(); i != hs.end(); i++)
	{
		cout << i->first << ", " << i->second << endl;
	}
	return 0;
}

출력 결과

yellowhat, headgear
bluesunglasses, eyewear
green_turban, headgear
728x90