按偶数和奇数排序

问题描述:

我想知道是否可以使用std :: sort函数按偶数或奇数对数字进行排序.

I would like to know is it possible to sort number by even or odd using the std::sort function.

我有以下代码,但我不确定如何在std :: sort

I have the following codes but i am not sure how to implement in the std::sort

inline bool isEven(const Point n) {
return n.getX()%2==0;
}

这是正确的

vector<Point> c;
std::sort(c.begin(),c.end(),isEven)

请咨询.

根据我对您的问题的了解,您希望将oddeven数字分开.如果是这样, std::partition 会做到这一点.

From what I understand of your question, you want to separate odd and even numbers. If that's the case, std::partition will do just that.

如果您想按升序排序并分别用oddeven数字进行排序,我将使用与这段代码类似的东西(不过,您仍然需要弄清楚您想要的Point的哪个部分进行排序)

If you want to sort by ascending values AND separate odd and even numbers, I would use something similar to this piece of code (still, you will have to figure out which component of your Point you want to sort on)

bool sortByEven(const int& left, const int& right)
{
    if(left & 1 && right & 1) // both are odd
    {
        return left < right;
    }
    else if(left & 1) // left is odd
    {
        return false;
    }
    else if(right & 1) // right is odd
    {
        return true;
    }

    // both are even
    return left < right;
}

此功能可以与 std::sort 一起使用,这是一个简短示例:

This function can be used with std::sort, here's a short example:

std::vector<int> numbers;
numbers.push_back(-1);
numbers.push_back(5);
numbers.push_back(12);
numbers.push_back(7);
numbers.push_back(-31);
numbers.push_back(-20);
numbers.push_back(0);
numbers.push_back(41);
numbers.push_back(16);

std::sort(numbers.begin(), numbers.end(), sortByEven);

将为您提供以下输出:

-20 0 12 16 -31 -1 5 7 41

对于其他类型,只需更改int或将其设置为template参数

For other types simply change the int or make it a template parameter