Software Workshop

C++14 이전에는 map이나 set 등의 연관 컨테이너(associative container)에 대해 find()를 호출할 때 파라미터로 key에 해당하는 값만 사용할 수 있었다.

C++14에서는 key가 아닌 값을 파라미터로 사용하더라도 비교만 가능하다면 find()가 정상적으로 동작할 수 있도록 구현할 수 있다. 바로 < 연산자나 () 연산자를 재정의하고 지원하고자 하는 파라미터 타입을 처리해주면 find()에서도 해당 파라미터 타입을 사용할 수 있게 되었다.

아래 예제에서 set<product, less<>> products2가 comparator로 less<>를 사용하고 < 연산자를 재정의하였음을 확인할 수 있다. find()의 파라미터로 문자열 대신에 struct product 타입의 값이 통째로 사용된 것에 주목할 것

#include <iostream>
#include <cstring>
#include <set>
#include <map>

using namespace std;

struct product {
    string name;
    string description;
    double price;
};

bool operator<(const product& p1, const product& p2) {
    return p1.name < p2.name;
}
ostream& operator<<(ostream&os, const product& p1) {
    os << "{ " << p1.name << ", " << p1.description << ", " << p1.price << " }";
    return os;
}

bool operator<(const product& p1, const string& str2) {
    return p1.name < str2;
}
bool operator<(const string& str1, const product& p2) {
    return str1 < p2.name;
}

int main(void) {
    set<product> products {
                           {"car", "this is a super car", 100000.0 },
                           { "ball", "a cheap but nice-looking ball", 100.0 },
                           { "orange", "fresh orange", 50.0}
    };
    auto it1 = products.find({"car", "", 0.0});
    if (it1 != products.end()) {
        cout << *it1 << endl;
    }

    // only in c++14
    set<product, less<>> products2 {
        {"car", "this is a super car", 100000.0 },
            { "ball", "a cheap but nice-looking ball", 100.0 },
                { "orange", "fresh orange", 50.0}
    };
    auto it2 = products2.find("ball");
    if (it2 != products2.end()) {
        cout << *it2 << endl;
    }

    return 0;
}
{ car, this is a super car, 100000 }
{ ball, a cheap but nice-looking ball, 100 }