Sort by Even and Odd numbers
c++, sorting, stdvector
Solution
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.
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;
}
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);
Will give you the following output:
-20 0 12 16 -31 -1 5 7 41
For other types simply change the `int` or make it a `template` parameter
Problem
I would like to know is it possible to sort number by even or odd using the std::sort function. 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; } ``` Is this correct ``` vector<Point> c; std::sort(c.begin(),c.end(),isEven) ``` Please advice.