• Home
  • About
    • Jiwon Jeong photo

      Jiwon Jeong

      끊임없이 배우며 성장하는 엔지니어

    • Learn More
    • Email
    • Github
  • Posts
    • All Posts
    • All Tags
    • All Categories
  • Projects

해시 알고리즘

22 May 2021

Reading time ~2 minutes

해시

  • 키에 대응되는 값을 저장하는 자료구조
  • insert, erase, find, update 연산

STL

unordered_set

void unordered_set_example(){
    unordered_set<int> s;
    s.insert(-10); s.insert(100); s.insert(15); // {-10, 100, 15}
    s.insert(-10) // {-10, 100, 15}
    cout << s.erase(100) << '\n'; //{-10, 15}, 1
    cout << s.erase(20) << '\n'; //{-10, 15}, 0
    if(s.find(15) != s.end()){
        cout << "15 in s\n"; //s.find 함수는 iterator를 반환. 찾아서 없으면 s.end() 반환
    } 
    else{
        cout << "15 not in s\n";
    } 
    cout << s.size() << '\n'; // 2
    cout << s.count(50) << '\n'; // 0
    for(auto e : s) cout << e << ' ';
    cout << '\n';
}

unordered_multiset

void unordered_multiset_example(){
    unordered_multiset<int> ms;
    s.insert(-10); s.insert(100); s.insert(15); // {-10, 100, 15}
    s.insert(-10) // {-10, -10, 100, 15}
    cout << ms.size() << '\n'; // 4
    for(auto e : s) cout << e << ' ';
    cout << '\n';
    cout << ms.erase(15) << '\n'; // {-10, -10, 100}, 2
    //ms.erase(-10)  => 이러면 모든 -10이 다 지워짐. 대신, 아래의 방법으로 하나만 지울 수 있음
    ms.erase(ms.find(-10)); // {-10, 100}
    ms.insert(100);
    cout << ms.count(100) << '\n';
}

unordered_map

#include <iostream>
#include <cstring>
#include <string>
#include <unordered_map>
using namespace std;

unordered_map<string, int> m;

int main() {
    
    
    m["hi"] = 123;
    m["bkd"] = 1000;
    cout << m.size() << '\n'; // 2
    m["hi"] = -7;
    if(m.find("hi") != m.end()){
        cout << "hi in s\n"; //s.find 함수는 iterator를 반환. 찾아서 없으면 s.end() 반환
    } 
    else{
        cout << "hi not in s\n";
    }
    m.erase("bkd");
    for(auto it = m.begin(); it != m.end(); it++){
        cout << it->first << ' ' << it->second << '\n';
    }

}

백준 - 회사에 있는 사람

#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <map>
#include <vector>

using namespace std;

map<string, string> m;
int n;

bool compare(pair<string, string> a, pair<string, string> b){
    if(a.first > b.first){
        return true;
    }else{
        return false;
    }
}

int main() {
    
    scanf("%d", &n);

    for(int i=0; i<n; i++){
        string name, flag;
        cin >> name >> flag;
        if(flag == "enter"){
            m[name] = flag;
        }else{
            m.erase(name);
        }
        
        
    }
    
    vector<pair<string, string>> v(m.begin(), m.end());

    sort(v.begin(), v.end(), compare);
    
    for(auto it = v.begin(); it!=v.end(); it++){
        cout << it->first << '\n';
    }
    


}


Algorithm Share Tweet +1