* set / multiset 모두 BST(Binary Search Tree) 형태의 자료 구조이다.
[ Set ]
- 중복을 허용하지 않는 자료 구조. (중복을 허용하려면 multiset을 사용해야 함.)
- 원소들은 자동으로 정렬된다. (insert)
#include <stdio.h>
#include <set>
int main(void)
{
using namespace std;
set<int> setTest;
setTest.insert(3);
setTest.insert(4);
setTest.insert(1);
setTest.insert(2);
setTest.insert(2);
setTest.insert(4);
setTest.erase(5);
printf("%d\n", *setTest.find(4)); // 4
if (setTest.find(5) == setTest.end())
{
printf("5는 존재하지 않음.\n");
}
printf("%d\n", setTest.count(4)); // 1
printf("%d\n", setTest.count(5)); // 0
printf("=== 순서대로 출력 ===\n");
for (auto it = setTest.begin(); it != setTest.end(); it++)
{
printf("Value = %d\n", *it); // 1,2,3,4
}
printf("\n=== 역순으로 출력 ===\n");
for (auto it = setTest.rbegin(); it != setTest.rend(); it++)
{
printf("Value = %d\n", *it); // 4,3,2,1
}
auto lowerbound2 = setTest.lower_bound(2);
auto upperbound2 = setTest.upper_bound(2);
printf("lower_bound(2) = %d\n", *lowerbound2); // 2보다 작지 않은 처음 원소는?
printf("upper_bound(2) = %d\n", *upperbound2); // 2보다 크지 않은 마지막 원소 다음은?
// 2를 초과하는 첫 원소의 위치
return 0;
}
[ multiset ]
- set과 달리 중복을 허용하는 자료 구조.
- 동일하게 #include <set>을 사용
- 사용법은 set과 동일하며, 위 예제에서 multiset을 set으로 바꿔주면 된다.
'Algorithm > Data Structure' 카테고리의 다른 글
[Leetcode] Binary Tree Preorder Traversal (0) | 2021.07.05 |
---|---|
4. LinkedList 구현하기 (0) | 2021.02.03 |
3. 동적 배열 구현 (0) | 2021.01.30 |
2. 큐(Queue) / 원형큐(Circular Queue) (0) | 2018.08.04 |
1. 스택(Stack) (0) | 2018.08.04 |