«   2024/03   »
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
Archives
Today
Total
03-28 16:32
관리 메뉴

lancelot.com

is_transparent 본문

프로그래밍

is_transparent

lancelot50 2022. 7. 30. 16:11
  • 객체 뿐만아니라 비교 기준이 되는 멤버 값으로도 검색 가능하게 하려면
    1. People 객체와 문자열로 비교 가능해야한다
    2. 비교 함수객체안에 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;
}