본문으로 바로가기

순서가 지정된 연관 컨테이너 ( map, multimap, set, multiset ) 이 자료형이 다른 조회를 지원합니다.

다시 말해, find() 및 lower_bound() 같은 멤버 함수의 키 또는 요소와 정확히 같은 형식을 전달할 필요가 없습니다.

대신 오버로드된 operator<가 정의되어 있어야 하며 키 형식 비교가 가능해야 합니다.


다음 예제에서는 std::set 컨테이너를 통해 A 라는 클래스를 받고, A::id 와 string을 비교하는 방법입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using namespace std;
 
class A {
public:
    A(const string& rhs) : id(rhs) {}
    bool operator<(const A& rhs) const { return id < rhs.id; }
    const std::string getid() const { return id; }
private:
    string id;
    friend bool operator<(const string& lhs, const A& rhs);
    friend bool operator<(const A& lhs, const string& rhs);
};
 
bool operator<(const string& lhs, const A& rhs){
    return lhs < rhs.id;
}
bool operator<(const A& lhs, const string& rhs) {
    return lhs.id < rhs;
}
 
int main() {
    A a1{ "ABC"s };
    A a2{ "AAA"s };
    A a3{ "ACB"s };
    A a4{ "BCA"s };
 
    set<A> myAset;    // 기본 인자는 less<>
 
    myAset.insert(a1);
    myAset.insert(a2);
    myAset.insert(a3);
    myAset.insert(a4);
 
    auto it = myAset.find(string("ABC"));
    if (it != myAset.end())
        cout << it->getid() << endl;    // ABC
    else
        cout << " not found " << endl;
}
cs

myAset의 키인 A 와 string 을 비교합니다. 
A는 기본으로 자신의 id 와 임시객체 string 의 비교연산을 지원합니다.

map, multimap, set, multiset 의 다음 멤버 함수들은 자료형이 다른 조회를 지원합니다.

1. find
2. count
3. lower_bound
4. upper_bound
5. equal_range