프로그래밍
is_transparent
lancelot50
2022. 7. 30. 16:11
- 객체 뿐만아니라 비교 기준이 되는 멤버 값으로도 검색 가능하게 하려면
- People 객체와 문자열로 비교 가능해야한다
- 비교 함수객체안에 is_transparent 멤버타입이 있어야한다. (C++14)
- 신기하네... 나중에 시간나면 더 찾아봐야겠다.
#include<iostream>
#include<set>
struct People
{
std::string name;
int age;
People(std::string name, int age) : name{ name }, age{ age } { }
};
struct PeopleCompare
{
bool operator()(const People& p1, const People& p2) const
{
return p1.name < p2.name;
}
bool operator()(const People& p1, std::string_view name) const
{
return p1.name < name;
}
bool operator()(std::string_view name, const People& p1) const
{
return name < p1.name;
}
using is_transparent = int; // C++14
};
int main()
{
std::set<People, PeopleCompare> s;
s.emplace("kim", 20);
s.emplace("lee", 25);
s.emplace("park", 40);
s.emplace("choi", 30);
auto p = s.find({ "kim", 20 }); // People("kim", 20)
// People 을 검색할때, name으로만 검색하니, s.find("kim") 만 넣을수는 없을까?
// 1. PeopleCompare 에 People 과 std::string 을 비교할 수있는 operator를 제공한다
// 2. PeppleCompare 에 is_transparent 멤버를 생성해준다 (C++14)
p = s.find("kim");
std::cout << p->name << std::endl;
std::cout << p->age << std::endl;
}