본문 바로가기
오래된 글

C++ STL Sets 사용하는 방법과 멤버 함수

by pagehit 2019. 4. 23.
반응형

C++ STL Sets

집합은 C++ 표준 템플릿 라이브러리 중 하나이다.
집합(Sets)은 특정한 순서로 특정 원소를 저장하는 컨테이너(container)이다.

주로 사용되는 함수들은 아래와 같다.
선언은 다음과 같이 한다.

sets<int> s; // creates a set of integers

집합의 크기는 다음과 같이 구할 수 있다.

int length = s.size(); // gives the size of the set.

집합에 새로운 원소는 insert() 함수를 이용한다.

s.insert(x); // inserts an integer x into the set s

원소를 지울 때는 erase() 함수를 이용한다.

s.erase(val); // erases an integer val from the set s.

집합에서 원소를 찾는 방법은 다음과 같다.

set<int>::iterator itr = s.find(val); // gives the iterator to the element val if it is found otherwise returns s.end()

예제

https://www.hackerrank.com/challenges/cpp-sets/problem?h_r=next-challenge&h_v=zen&isFullScreen=true

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int Q; // the number of queries
    int y, x; // y is the type of the query and x is an integer
    set<int> s;
    cin >> Q;

    for(int i = 0; i < Q; i++) {
        cin >> y >> x;
        if(y == 1) {
            s.insert(x);
        }
        else if(y == 2) {
            s.erase(x);
        }
        else if(y == 3) {
            if(s.find(x) == s.end()) {
                cout << "No" << endl;
            }
            else {
                cout << "Yes" << endl;
            }
        }
    }

    return 0;
}

참고

2019/04/23 - [C++] - C++ Lower Bound-STL 사용하는 방법

2019/04/23 - [C++] - C++ 반복자란 무엇인가?

2019/04/20 - [C++] - C++ 벡터 특정 원소 지우는 방법 vector.erase()

2019/04/20 - [C++] - C++ vector를 이용해 정렬하는 방법

2019/04/19 - [C++] - C++ 벡터를 이용해서 길이가 다양한 이차원 배열 구현하기

2019/04/04 - [C++] - C++ | #include <bits/stdc++.h> 헤더파일이란 무엇인가?

2019/04/02 - [C++] - C++ 강의 | 조건문 if와 if - else 문 그리고 if - else if -else 문

2019/04/02 - [C] - C/C++ printf 함수에서 실수 소수점 자리와 너비를 지정하는 방법 | 숫자 정렬해서 출력하기, 소수점 아래 자리수 지정하기

2019/04/01 - [C++] - C++ 강의 | 기본 데이터 타입과 형식지정자 그리고 C++의 출력과 입력 scanf와 printf

반응형

댓글