Sort std::vector but ignore a certain number

前端 未结 6 613
我寻月下人不归
我寻月下人不归 2021-01-28 12:05

I have an std::vector of the size 10 and each entry is initially -1. This vector represents a leaderboard for my game (high scores), and -1 just means th

6条回答
  •  醉梦人生
    2021-01-28 12:26

    std::sort supports using your own comparison function with the signature bool cmp(const T& a, const T& b);. So write your own function similar to this:

    bool sort_negatives(const int& a, const int& b)
    {
        if (a == -1) {
            return false;
        }
        if (b == -1) {
            return true;
        }
        return a < b;
    }
    

    And then call sort like std::sort(myVector.begin(), myVector.end(), sort_negatives);.

    EDIT: Fixed the logic courtesy of Slava. If you are using a compiler with C++11 support, use the lambda or partition answers, but this should work on compilers pre C++11.

提交回复
热议问题