-
[Data Stucture] map(๋งต) ์ฌ์ฉ๋ฒData Structure 2020. 2. 22. 18:58๋ฐ์ํ
- C++ STL ์ค ํ๋์ธ map์ ๋ํ ์ค๋ช ์ ๋๋ค.
map ์ด๋?
map์ key์ value์ ์กฐํฉ์ผ๋ก ๊ตฌ์ฑ๋ container ์ ๋๋ค.
map์ key์ compare ํจ์๋ฅผ ํตํด ์ ๋ ฌ๋ฉ๋๋ค. (๊ธฐ๋ณธ์ ์ผ๋ก ์ค๋ฆ์ฐจ์)
์ ๋๋ฆญ์ผ๋ก ๊ตฌํ๋์ด key์ value๋ ์ด๋ ํ type์ด ์ฌ ์ ์์ต๋๋ค.
map์ binary search tree๋ก ๊ตฌ์ฑ๋์ด ์์ด์ unordered_map์ ๋นํด ํ์์ด ๋๋ฆฝ๋๋ค. (์๊ฐ ๋ณต์ก๋ O(log n))
map์ ์ค๋ณต์ ํ์ฉํ์ง ์๊ณ ์ค๋ณต key๋ฅผ ๊ฐ์ง๊ธฐ ์ํด์๋ multimap์ ์ฌ์ฉํด์ผ ํฉ๋๋ค.
#include < map > ์ ์ ์ธํด์ผ map ์ ์ฌ์ฉํ ์ ์์ต๋๋ค.
๊ธฐ๋ณธ ํจ์
empty ( )
- ๋งต์ด ๋น์ด์๋์ง ํ์ธํ๋ ํจ์
- if map is empty, then return 1 else 0
size ( )
- ๋งต์ ํฌ๊ธฐ๋ฅผ ๋ฐํํ๋ ํจ์
- return size_type (unsigned int)
operator [ ]
- ๋งต์์ key๋ฅผ ํตํด value๋ฅผ ์ง์ ํ๋ operator
insert ( {key, value} )
- ๋งต์ pair<key, value>๋ฅผ ์ถ๊ฐํ๋ ํจ์
- if key is contained, then not insert
- insert ํ๋ ๋ฐฉ๋ฒ : pair ์ถ๊ฐ, ํน์ position์ pair ์ถ๊ฐ, ๋ฒ์ ์ถ๊ฐ
erase ( key )
- ๋งต์์ key์ ํด๋นํ๋ ์์๋ฅผ ์ญ์ ํ๋ ํจ์
- erase ํ๋ ๋ฐฉ๋ฒ : ํน์ position์ pair ์ญ์ , key๋ก ๊ฒ์ํ์ฌ ์ญ์ , ๋ฒ์ ์ญ์
swap ( )
- ๋ ๊ฐ์ ๋งต์ ๋ฐ๊พธ๋ ํจ์
clear ( )
- ๋งต์ ์ด๊ธฐํ ํ๋ ํจ์
find ( key )
- ๋งต์์ key์ ํด๋นํ๋ ์์๊ฐ ์๋์ง ์ฐพ๋ ํจ์
- if key is contained, then iterator else map.end()
count ( key )
- ๋งต์์ key์ ํด๋นํ๋ ์์์ ๊ฐฏ์๋ฅผ ๋ฐํํ๋ ํจ์
- if key is contained, then 1 else 0
operator=
- ๋์ ์ฐ์ฐ์ ๊ฐ๋ฅ
ํ์ ๋ฐฉ๋ฒ
- index๋ก ์ ๊ทผํ ์ ์๊ณ iterator๋ฅผ ์ฌ์ฉํด์ ์์ฐจ์ ์ ๊ทผ์ด ๊ฐ๋ฅํ๋ค
- ์์ : begin(), ๋ : end()
- key : iter->first, value : iter->second
- ๋ฐ๋ณต๋ฌธ์ผ๋ก ํ์ํ ๊ฒฝ์ฐ auto ํ์ฉ
์ค์ต
This file contains 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<map> using namespace std; int main(){ map<string,int> m; if(m.empty()){ cout<<"map์ด ๋น์ด์์ต๋๋ค"<<endl; } m["c"] = 4; m.at("c") = 3; m.insert(make_pair("b",2)); m.insert({"a",1}); for(map<string,int>::iterator iter = m.begin();iter!=m.end();iter++){ cout<<"key : "<<iter->first<<" ์ ํด๋นํ๋ value : "<<iter->second<<" ์ ๋๋ค"<<endl; } m.erase("c"); cout<<"map์ ํฌ๊ธฐ๋ "<<m.size()<<" ์ ๋๋ค"<<endl; if (m.find("c")==m.end()) { m["c"] = 3; cout<<"map์ ํด๋นํ๋ key๊ฐ ์์ต๋๋ค"<<endl; } m.insert({"a",3}); m.insert({"a",4}); m.insert({"a",5}); cout<<"map์์ key๊ฐ a์ ํด๋นํ๋ value ์ ๊ฐฏ์๋ "<<m.count("a")<<" ์ ๋๋ค"<<endl; for(auto elem : m){ cout<<"key : "<<elem.first<<" ์ ํด๋นํ๋ value : "<<elem.second<<" ์ ๋๋ค"<<endl; } } ๊ฒฐ๊ณผ
- ์ถ๊ฐ๋ก ๊ถ๊ธํ ์ ์ด๋ ์์ ํ ์ฌํญ ์์ผ๋ฉด ๋๊ธ๋ก ๋จ๊ฒจ์ฃผ์ธ์.
๋ฐ์ํ'Data Structure' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Data Structure] unordered_map ์ฌ์ฉ๋ฒ (6) 2020.03.16 [Data Structure] Priority_queue(์ฐ์ ์์ ํ) ์ฌ์ฉ๋ฒ (0) 2020.03.16 [Data Structure] pair(ํ์ด) ์ฌ์ฉ๋ฒ (0) 2020.03.13 [Data Stucture] Queue (ํ) ์ฌ์ฉ๋ฒ (0) 2020.02.22 [Data Stucture] Stack(์คํ) ์ฌ์ฉ๋ฒ (0) 2020.02.22