unordered map

도경원·2023년 7월 16일
0

C++

목록 보기
2/2

unordered map 배열


unodered map 으로 배열을 만드는 문제가 헷갈렸다

#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

unordered_map<string, int> a;

void main() {
	// Create an unordered map of three strings (that map to strings)
	unordered_map<string, string> u[2] = 
	{
		{
			{"RED" , "#FF0000"},
			{"GREEN" , "00FF00"},
			{"BLUE" , "#0000FF"}
		},
		{
			{"RED" , "new red"}
		}
	};
	cout << u[1]["RED"];
}

결과는 new red를 출력한다
int a[2] 는 int 자료형의 배열을 만들 듯 unordered_map<string, int> a는 unordered map 배열을 만든다. 헷갈릴 수 있는 부분이 map이 이미 배열처럼 여러 요소를 담기 때문에 2차원배열처럼 보일 수 있다는 점이다.

아니면 이미 배열처럼 보여서 unordered map을 두 개를 형성하는 지 눈치채지 못할 수도 있다.

중요한 점은 map 을 두 개 만든다는 점이다

unordered map 사용하기


오늘 프로그래머스 문제를 풀다가 unordered map에 대해 모호하게 알고 있단 걸 알게 되어 글을 쓴다

#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

unordered_map<string, int> a;

void main() {
	// Create an unordered map of three strings (that map to strings)
	unordered_map<string, string> u = 
	{
		{"RED" , "#FF0000"},
		{"GREEN" , "00FF00"},
		{"BLUE" , "#0000FF"}
	};

	// 람다를 적는 방식
	auto print_key_value = [](const auto& key, const auto& value) {
		cout << "Key:[" << key << "] Value:[" << value << "]\n";
	};

	// unordered map 은 pair 로 구성되어 있다
	for (const pair<const string, string>& n : u)
	{
		print_key_value(n.first, n.second);
	}

	//Add two new entries to the unordered_map
	u["BLACK"] = "#000000";
	u["WHITE"] = "#FFFFFF";

	cout << "\nOutput values by key:\n"
			"The HEX of color RED is:[" << u["RED"] << "]\n"
			"The HEX of color BLACK is:[" <<u["BLACK"] << "]\n\n";
	cout << "Use operator[] with non-existent key to insert a new key-value pair:\n";
	print_key_value("new_key", u["new_key"]);

	cout << "\nIaterate and print key-value pairs, using 'auto';\n";
			"new_key is now one of the keys in the map:\n";


	for (const auto& n : u)
		print_key_value(n.first, n.second);

}

결과


Key:[GREEN] Value:[00FF00]
Key:[RED] Value:[#FF0000]
Key:[BLUE] Value:[#0000FF]

Output values by key:
The HEX of color RED is:[#FF0000]
The HEX of color BLACK is:[#000000]

Use operator[] with non-existent key to insert a new key-value pair:
Key:[new_key] Value:[]

Iaterate and print key-value pairs, using 'auto';
Key:[BLACK] Value:[#000000]
Key:[GREEN] Value:[00FF00]
Key:[RED] Value:[#FF0000]
Key:[BLUE] Value:[#0000FF]
Key:[WHITE] Value:[#FFFFFF]
Key:[new_key] Value:[]

auto와 pair 둘 모두로 접근가능하다

index로 접근하고 싶을 때는 iterator를 사용하고
u[key] 처럼 키로써 보통 접근한다

pair 로 요소들이 구성되어 있어서 요소 접근 후에는 .first .second로 접근한다

람다에 대한 글
https://blockdmask.tistory.com/491

profile
DigitalArtDeveloper

0개의 댓글