C++ Sorting the “percentage” of two paired integer arrays

后端 未结 3 448
鱼传尺愫
鱼传尺愫 2021-01-27 11:54

I have a program with 2 \"paired\" integer arrays newNumerator[ ], and newDenominator[ ] which both have 9 integers in them. I wrote a function that sorts them in ascending ord

3条回答
  •  北海茫月
    2021-01-27 12:44

    I propose using the STL for sorting. Makes things simpler and more understandable.

    #include 
    #include 
    
    struct Ratio
    {
        int numerator;
        int denominator;
    
        double toDouble() const
        {
            return static_cast(numerator)
                 / static_cast(denominator);
        }
    
        bool operator < (Ratio const& other) const
        {
            return toDouble() < other.toDouble();
        }
    };
    
    void main()
    {
        std::vector ratios = { {1, 2}, {5, 7}, {2, 11} };
        std::sort(ratios.begin(), ratios.end());
    }
    

    Dealing with raw arrays and sorting manually is almost always the more tedious and error prone approach.

    See http://en.cppreference.com/w/cpp/algorithm/sort and http://en.cppreference.com/w/cpp/container/vector for reference

提交回复
热议问题