unordered_set<T> 란?
정렬되지 않은 HashSet의 자료구조로 구현된 C++ STL을 의미한다.
먼저, HashSet이란 Hashing을 기반으로 데이터를 관리해주는 자료구조를 의미한다.
따라서, 삽입, 삭제, 탐색 등 모든 함수의 시간 복잡도가 O(1) time 이다.
[코드트리 조별과제 2주차] unordered_map<K, V> 사용 방법 | C++ STL
unordered_map이란?정렬되지 않은 HashMap의 자료구조로 구현된 C++ STL를 의미한다. 먼저, HashMap이란 Dictionary를 구현하는 방법의 일부로, pair로 구성된 entry를 원소로 저장하는 컨테이너를 의미한다.Hash
logicallaw.tistory.com
위 블로그 글에서는 unordered_map<K, V>에 대해 설명을 해놓았는데, unordered_map은 Key와 Value를 쌍으로 entry로 관리되어 특정 Key에 대한 Value를 하나의 쌍으로 관리할 때 주로 사용되는 반면, unordered_set은 중복을 허락하지 않고 데이터를 관리할 때 주로 사용된다.
unordered_set<T>의 include 방법
#include <unordered_set>
다음과 같이 unordered_set 헤더를 include하면 사용할 수 있다.
주요 메서드
unordered_set의 메서드는 unordered_map의 메서드의 사용 방법과 매우 유사하다.
주요 메서드를 설명하기 전, 아래 코드를 기준으로 설명하겠다.
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
unordered_set<string> set;
return 0;
}
삽입 메서드(insert)
set.insert(E)로 HashSet에 데이터 E를 추가한다.
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
unordered_set<string> set;
//삽입 메서드
set.insert("John");
set.insert("Park");
set.insert("Lee");
set.insert("Kim");
return 0;
}
이때, unordered_map의 삽입 연산에서는 map[K] = V;와 같이 배열처럼 삽입할 수 있는 방법이 제공되었지만, unordered_set에서는 지원하지 않는다.
삭제 메서드(erase)
set.erase(E)로 현재 HashSet에 들어있는 데이터 중 E를 찾아 제거한다.
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
unordered_set<string> set;
//삽입 메서드
set.insert("John");
set.insert("Park");
set.insert("Lee");
set.insert("Kim");
//삭제 메서드
set.erase("Lee");
set.erase("Kim");
return 0;
}
탐색 메서드(find)
set.find(E)로 현재 HashSet에 데이터 E가 존재하면 E의 iterator를 리턴하고, 없다면 set.end()를 리턴한다.
이 메서드는 주로 조건문에서 현재 HashSet에 데이터 E의 존재 여부를 확인할 때 주로 사용된다.
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
unordered_set<string> set;
//삽입 메서드
set.insert("John");
set.insert("Park");
set.insert("Lee");
set.insert("Kim");
//삭제 메서드
set.erase("Lee");
set.erase("Kim");
//탐색 메서드
if(set.find("John") != set.end()) {
cout << "existed!" << endl; //existed!
} else {
cout << "not existed!" << endl;
}
return 0;
}
보조 메서드
size 메서드 | 현재 HashSet에 존재하는 데이터의 개수를 리턴한다.
set.size()로 데이터의 개수를 리턴받아 확인할 수 있다.
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
unordered_set<string> set;
//삽입 메서드
set.insert("John");
set.insert("Park");
set.insert("Lee");
set.insert("Kim");
//삭제 메서드
set.erase("Lee");
set.erase("Kim");
//탐색 메서드
if(set.find("John") != set.end()) {
cout << "existed!" << endl; //existed!
} else {
cout << "not existed!" << endl;
}
//size 메서드
cout << set.size() << endl; //2
return 0;
}
'PS > 코드트리' 카테고리의 다른 글
[코드트리] +1-1 Technique | C++ (0) | 2024.08.30 |
---|---|
[코드트리 조별과제 3주차] priority_queue<T> 사용 방법 | C++ STL (0) | 2024.07.29 |
[코드트리 조별과제 2주차] unordered_map<K, V> 사용 방법 | C++ STL (0) | 2024.07.23 |
[코드트리 조별과제 1주차] 연속되는 수 3 (0) | 2024.07.18 |