구조체를 자료형으로 사용하는 set,map

jh Seo·2023년 6월 26일
0

C++공부

목록 보기
19/21

개요

set에 stock 구조체를 자료형으로 사용하려다가 막혀서 작성한 글이다.

접근방식

https://chanhuiseok.github.io/posts/algo-46/

해당 구조체 내부에 연산자< 오버로딩

stock구조체는

struct stock {
    int price;
    int index; 
    int enteredTime;
};

이렇게 생겼고, 단순히 set<stock> s로 선언하니 오류가 났다.

오류 C2678 이항 '<': 왼쪽 피연산자로 'const _Ty' 형식을 사용하는 연산자가 없거나 허용되는 변환이 없습니다.

따라서 set은 <연산자를 사용하는구나 하고 <연산자를 오버로딩해줬다.

struct stock {
    int price;
    int index; 
    bool operator<( const stock& other) {
        return index <= other.index;
    }
};

그래도 오류가 계속 나서 다시 한번 오류를 읽어보니

왼쪽 피연산자로 'const _Ty' 형식을 사용하는

왼쪽 피연산자가 const_Ty형식을 사용해야 한다.
따라서 함수에 const를 붙여 멤버변수도 변경을 못하게 해주니 해결되었다.

struct stock {
    int price;
    int index; 
    bool operator<( const stock& other)const {
        if (index != other.index)
            return index < other.index;
        else if (price != other.price) return price < other.price;
        return false;
    }
};

set<stock> s;

구조체 밖에 선언

구조체 밖에 비교함수를 선언하려면

struct stock {
   int price;
   int index; 
};

struct compare {
   bool operator()(const stock& a, const stock& b)const {
       if (a.index != b.index) return a.index <= b.index;
       else if (a.price != b.price) return a.price <= b.price;
       return false;
   }
};

이런식으로 stock 구조체 인자 두개를 받아 연산자 ()를 오버로딩해주면 된다.

생각

주의할 점은 strict weak ordering을 만족해야한다.
비교함수에서 만약 두값이 같다면 false를 리턴해야한다!

profile
코딩 창고!

0개의 댓글