c++11 이후 표준으로 포함된 unordered_map,set
둘다 일반 (ordered)map,set 과 내부 구조는 아예 다르다
사용방법 이 비슷하기에이름이 같은 map,set 일 뿐
(ordered)map ,set 은 트리구조로 되어 있어 삽입하며 정렬되고 정렬된만큼 검색은 Ologn
unordered_map,set 은 hashtable 기반으로 키를 hash 를 만들고 배치하고 접근하기 때문에 삽입할때 O1, 탐색할때 O1
random access 가 가능하며 [ ] 연산자로 접근 가능하다
https://en.cppreference.com/w/cpp/container/unordered_map
#include <iostream>
#include <string>
#include <unordered_map>
int main()
{
// Create an unordered_map of three strings (that map to strings)
std::unordered_map<std::string, std::string> u = {
{"RED","#FF0000"},
{"GREEN","#00FF00"},
{"BLUE","#0000FF"}
};
std::cout << "Iterate and print keys and values of unordered_map, being explicit with\n"
"the type of the iterator, n:\n";
for( const std::pair<std::string, std::string>& n : u ) {
std::cout << "Key:[" << n.first << "] Value:[" << n.second << "]\n";
}
std::cout << "Iterate and print keys and values of unordered_map, using auto:\n";
for( const auto& n : u ) {
std::cout << "Key:[" << n.first << "] Value:[" << n.second << "]\n";
}
std::cout << "Iterate and print keys and values using structured binding (since C++17):\n";
for( const auto& [key, value] : u ) {
std::cout << "Key:[" << key << "] Value:[" << value << "]\n";
}
// Add two new entries to the unordered_map
u["BLACK"] = "#000000";
u["WHITE"] = "#FFFFFF";
std::cout << "Output values by key:\n";
std::cout << "The HEX of color RED is:[" << u["RED"] << "]\n";
std::cout << "The HEX of color BLACK is:[" << u["BLACK"] << "]\n";
}
댓글 남기기