-
[Data Structure] unordered_map ์ฌ์ฉ๋ฒData Structure 2020. 3. 16. 22:04๋ฐ์ํ
- C++ STL์ค ํ๋์ธ unordered_map์ ๋ํ ์ค๋ช ์ ๋๋ค.
unorderd_map
map๋ณด๋ค ๋ ๋น ๋ฅธ ํ์์ ํ๊ธฐ ์ํ ์๋ฃ๊ตฌ์กฐ์ ๋๋ค.
unordered_map์ ํด์ฌํ ์ด๋ธ๋ก ๊ตฌํํ ์๋ฃ๊ตฌ์กฐ๋ก ํ์ ์๊ฐ๋ณต์ก๋๋ O(1)์ ๋๋ค.
map์ Binary Search Tree๋ก ํ์ ์๊ฐ ๋ณต์ก๋๋ O(log n)์ ๋๋ค.
unordered_map์ ์ฌ์ฉํ๊ธฐ ์ํด์๋ #include< unordered_map > ์ ์ ์ธํด์ผ ํฉ๋๋ค.
unordered_map์ ์ค๋ณต๋ ๋ฐ์ดํฐ๋ฅผ ํ์ฉํ์ง ์๊ณ map์ ๋นํด ๋ฐ์ดํฐ๊ฐ ๋ง์ ์ ์๋ฑํ ์ข์ ์ฑ๋ฅ์ ๋ณด์ ๋๋ค.
ํ์ง๋ง, key๊ฐ ์ ์ฌํ ๋ฐ์ดํฐ๊ฐ ๋ง์ ์ ํด์ ์ถฉ๋๋ก ์ธํด ์ฑ๋ฅ์ด ๋จ์ด์ง ์๋ ์์ต๋๋ค.
ํจ์
empty( )
- ๋งต์ด ๋น์ด์๋์ง ํ์ธํ๋ ํจ์
- if unordered_map is empty, then return 1 else 0
size( )
- ๋งต์ ํฌ๊ธฐ๋ฅผ ํ์ธํ๋ ํจ์
- return size_type ( unsigned int )
operator [ ]
- ๋งต์์ key๋ฅผ ํตํด value๋ฅผ ์ง์ ํ๋ operator
- map_name[key] = value
find( key )
- ๋งต์์ key์ ํด๋นํ๋ ์์๋ฅผ ์ฐพ๋ ํจ์
- if key is contained, then iterator else map_name.end()
count( key )
- ๋งต์์ key์ ํด๋นํ๋ ์์์ ๊ฐฏ์๋ฅผ ๋ฐํํ๋ ํจ์
- if key is contained, return 1 else 0
insert( {key, value} )
- ๋งต์ pair<key,value> ๋ฅผ ์ถ๊ฐํ๋ ํจ์
- if key is contained, then not insert
erase( key )
- ๋งต์์ key์ ํด๋นํ๋ ์์๋ฅผ ์ ๊ฑฐํ๋ ํจ์
- erase ํ๋ ๋ฐฉ๋ฒ : ํน์ position์ pair ์ญ์ , key๋ฅผ ํตํด ์ญ์ , ๋ฒ์ ์ญ์
clear( )
- ๋งต์ ์ด๊ธฐํํ๋ ํจ์
operator =
- ๋์ ์ฐ์ฐ์ ๊ฐ๋ฅ
ํ์๋ฐฉ๋ฒ
- index๋ก ์ ๊ทผํ ์ ์๊ณ iterator๋ก ์ ๊ทผํ์ฌ์ผ ํ๋ค.
- ์์ : begin( ), ๋ : end( )
- key : iter->first, value : iter->second
- ๋ฐ๋ณต๋ฌธ ์ฌ์ฉ ์ auto ํ์ฉ or pair< key_type, value_type > ์ฌ์ฉ
์ค์ต
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters#include <iostream> #include <string> #include <unordered_map> using namespace std; int main(){ unordered_map<string,int> um; if(um.empty()){ cout<<"unordered_map์ ๋น์ด์์ต๋๋ค"<<endl; } um.insert(make_pair("key",1)); um["banana"]=2; um.insert({"melon",3}); cout<<"unordered_map์ ํฌ๊ธฐ๋ "<<um.size()<<" ์ ๋๋ค"<<endl; // auto๋ก ํด๋ ๋ฌด๋ฐฉ for(pair<string,int> elem : um){ cout<<"key : "<<elem.first<<" value : "<<elem.second<<endl; } // find ๋์ count๋ก ํ์ธ ๊ฐ๋ฅ if(um.find("banana")!=um.end()){ um.erase("banana"); } cout<<"unordered_map์ ํฌ๊ธฐ๋ "<<um.size()<<" ์ ๋๋ค"<<endl; for(auto elem : um){ cout<<"key : "<<elem.first<<" value : "<<elem.second<<endl; } return 0; } ๊ฒฐ๊ณผ
- ์ถ๊ฐ๋ก ๊ถ๊ธํ ์ ์ด๋ ์์ ํ ๋ถ๋ถ ์์ผ๋ฉด ๋๊ธ๋ก ๋จ๊ฒจ์ฃผ์ธ์.
๋ฐ์ํ'Data Structure' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Data Structure] multimap ์ฌ์ฉ๋ฒ (0) 2020.11.08 [Data Structure] Set ์ฌ์ฉ๋ฒ (0) 2020.03.19 [Data Structure] Priority_queue(์ฐ์ ์์ ํ) ์ฌ์ฉ๋ฒ (0) 2020.03.16 [Data Structure] pair(ํ์ด) ์ฌ์ฉ๋ฒ (0) 2020.03.13 [Data Stucture] map(๋งต) ์ฌ์ฉ๋ฒ (0) 2020.02.22