#43. map, set에 struct나 class 넣기
중복된 값을 피하고 싶을 때, map이나 set을 사용한다.
이때, map의 key값이나 set에 struct나 class를 넣고 싶을 때, 다음과 같이 연산자 오버로딩을 해주면 된다.
bool operator < (const class& other) const
{
return a<other.a;
}
이때 class의 특정한 변수가 중복되는 것을 피하고 싶을 때, (find도 마찬가지)
operator == 을 해주면 되지 않을까? 했지만 되지 않음
그 이유는 map이나 set의 동일 원소 판별 방법은 아래와 같음
...Two elements of a set are considered equivalent if the container's comparison object returns false reflexively (i.e., no matter the order in which the elements are passed as arguments).
위와 같이 map과 set의 동일 원소 판별은 a<b, b<a 를 두번 검사 하여, 둘다 false일 경우 다른원소라고 판별한다.
따라서 다음과 같이 연산자 오버로딩을 해주면 된다.
bool operator < (const class& other) const
{
if(a==other.a)
return false;
// 원하는 조건
return true;
}
이렇게 하게 되면 a라는 인자가 같을 때에는 중복 원소 라고 판별 하게 된다.
(unordered_map 이나 unordered_set의 경우에는 ==으로 판별한다)