728x90
728x90

multiset(중복 집합)

특징

  • 연관 컨테이너(Associative Container) 중 하나이다.
    • 연관 컨테이너에는 set, multiset, map, multimap 이 있다.
  • set과 비슷하지만, 중복된 키(Key)를 넣을 수 있다는 차이점이 있다.
  • 삽입된 요소들은 기본적으로 오름차순(less)으로 정렬된다.

set 과 multiset

 

헤더 파일

  • multiset을 사용하려면 다음의 헤더 파일을 불러와야 한다.
#include <set>

 

멤버 함수

 

사용 방법

 

[C++] set(집합)

set(집합) 특징 연관 컨테이너(Associative Container) 중 하나이다. 연관 컨테이너에는 set, multiset, map, multimap 이 있다. 특정 순서에 따라 고유한 요소를 저장하는 컨테이너이다. 기본적으로 요소들은 오

dev-astra.tistory.com

 

객체 생성

  • 다음과 같이 객체를 생성한다.
multiset<[data_type]> [name]
#include <iostream>
#include <set>
using namespace std;

multiset<int> ms {
    1, 1, 3, 10, 10, 3
};

int main() {    
    for (const auto& num : ms) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}
1 1 3 3 10 10

 

요소 삽입

  • 다음과 같이 insert() 함수를 사용하여 요소를 삽입할 수 있다.
  • set과 다르게 중복되는 요소를 삽입할 수 있다.
ms.insert(1);

 

키의 개수 알아내기

  • count([key]) 함수를 사용하여 키의 개수를 확인할 수 있다.
cout << ms.count(1) << endl;    // 키가 1인 요소의 개수 출력

 

내림차순으로 정렬시키기

  • 요소를 삽입할 때 기본적으로 오름차순(less)으로 정렬되지만, 다음과 같이 내림 차순(greater)으로 정렬시키도록 할 수 있다.
  • map에서도 이 방법을 사용할 수 있다.
#include <iostream>
#include <set>
#include <functional>   // less, greater
using namespace std;

struct myGreater {
    bool operator()(const int &lhs, const int &rhs) const {
        return lhs > rhs;   // 내림 차순으로 정렬
    }
};

struct myLess {
    bool operator()(const int &lhs, const int &rhs) const {
        return lhs < rhs;   // 오름 차순으로 정렬
    }
};


int main() {
    // 오름 차순으로 정렬 (기본값)
    set<int, less<int>> s1 { 3, 10, -1 };      //  set<int, myLesser> s1{3, 10, -1};
    
    for (const auto& num : s1) {
        cout << num << " ";
    }
    cout << endl;
    
    // 내림 차순으로 정렬
    set<int, greater<int>> s2 { 3, 10, -1 };   // set<int, myGreater> s2{3, 10, -1};

    for (const auto& num : s2) {
        cout << num << " ";
    }
    cout << endl;
    
    return 0;
}
-1 3 10 
10 3 -1

 

사용 예

#include <iostream>
#include <set>
using namespace std;

multiset<int> ms;

int main() {   
    // 요소 삽입
    ms.insert(12);
    ms.insert(10);
    ms.insert(2);
    ms.insert(10);
    ms.insert(90);
    ms.insert(85);
    ms.insert(45);
    
    cout << "multiset" << '\n';
	for (auto i : ms) {
        cout << i << " ";
    }
    
    cout << endl;
    
    // 요소 찾기
    auto search1 = ms.find(10);
    auto search2 = ms.find(90);
    
    // 요소 지우기 : [10, 90)
    ms.erase(search1, search2);
    
    cout << "multiset after erasing" << '\n';
    for (auto i : ms) {
        cout << i << " ";
    }
    
    cout << endl;
    
    ms.erase(ms.begin());    // 첫 번째 요소 제거
    for (auto i : ms) {
        cout << i << '\n';
    }
    
    return 0;
}
multiset
2 10 10 12 45 85 90 
multiset after erasing
2 90 
90

 

728x90
728x90