π Hash table
Hash table
π Hash table μ΄λ?
- ν€-κ°(key-value) μ λ°μ΄ν°λ₯Ό λΉ λ₯΄κ² μ μ₯νκ³ κ²μν μ μλ λ°μ΄ν° ꡬ쑰μ΄λ€.
- λ΄λΆμ μΌλ‘ ν΄μ ν¨μλ₯Ό μ¬μ©ν΄ λ°μ΄ν°λ₯Ό νΉμ λ²ν·(bucket) μ λ§€ννμ¬ (O(1)) μμ€μ νκ΅° κ²μ μκ°μ 보μ₯νλ€.
π Hash table ꡬν 컨ν μ΄λ
- unordered_map
- ν€-κ°(key-value) μμ μ μ₯νλ ν΄μ ν μ΄λΈ
- unordered_set
- μ€λ³΅ λμ§ μλ κ°λ§ μ μ₯νλ ν΄μ ν μ΄λΈ
π ꡬν μμ
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<string, int> hashTable; // unordered_map<key, value> λ³μλͺ
;
// λ°μ΄ν° μ½μ
hashTable["apple"] = 10;
hashTable["banana"] = 20;
// λ°μ΄ν° κ²μ
if (hashTable.find("apple") != hashTable.end()) {
cout << "Apple count: " << hashTable["apple"] << endl;
}
return 0;
}
π‘ μ£Όμ λ©μλ
| νΈμΆ | μ€λͺ |
|---|---|
| insert() | ν€ - κ° μ μ½μ |
| find() | ν€ κ²μ |
| erase() | νΉμ ν€ μμ |
| count() | ν€κ° μ‘΄μ¬νλμ§ νμΈ |
| at() | νΉμ ν€μ ν΄λΉνλ κ° λ°ν |
| bucket()_count() | λ²ν·μ κ°μ λ°ν |
| load_factor() | μμ μ / λ²ν· μ λΉμ¨ λ°ν |
| rehash() | λ²ν· κ°μλ₯Ό λλ € μΆ©λ ν΄κ²° |
π μκ° λ³΅μ‘λ
| Β | νκ· | μ΅μ |
|---|---|---|
| μ½μ | (O(1)) | (O(n)) |
| κ²μ | (O(1)) | (O(n)) |
| μμ | (O(1)) | (O(n)) |
π μ 리
- Hash tableμ λΉ λ₯Έ λ°μ΄ν° κ²μ μ ν΄μΌν λ μ μ©νλ€.
- unordered_map κ³Ό unordered_set λ κ°μ§κ° μ‘΄μ¬νλ€.
- unordered_map μ ν€-κ°(key-value) λ₯Ό κ°μ§κ³ μλ€.
- unordered_set μ μ€λ³΅ μλ κ° μ κ°μ§κ³ μλ€.