250x250
Notice
Recent Posts
«   2024/07   »
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
관리 메뉴

일상 코딩

[C++/9.04] 비교 연산자 오버로딩 본문

C++/따배C++ 09강 연산자 오버로딩

[C++/9.04] 비교 연산자 오버로딩

polarcompass 2021. 10. 29. 01:08
728x90

※ 비교 연산자 오버로딩시 주의점.

return 문 안에서

오름차순은 "<"으로 해주고,

내림차순은 ">"으로 

#include <iostream>
#include <vector>
#include <algorithm>
#include <random>

using namespace std;

class Cents
{
private:
    int m_cents;

public:
    Cents(int cents = 0) { m_cents = cents; }
    int getCents() const { return m_cents; }
    int &getCents() { return m_cents; }

    friend bool operator < (const Cents &c1, const Cents &c2)
    {
        return c1.m_cents < c2.m_cents;
    }

    friend std::ostream &operator << (std::ostream &out, const Cents &cents)
    {
        out << cents.m_cents;
        return out;
    }
};

int main()
{
    vector<Cents> arr(20);
    for (unsigned i = 0; i < 20; ++i)
        arr[i].getCents() = i;

    // C++17 이후 random은 이렇게 구현한다.
    std::random_device rd;
    std::mt19937 g(rd());
    std::shuffle(arr.begin(), arr.end(), g);

    for (auto &e : arr)
        cout << e << " ";
    cout << endl;

    // sorting
    std::sort(arr.begin(), arr.end());

    for (auto &e : arr)
        cout << e << " ";
    cout << endl;
}
728x90