我想知道是否可以使用 std::sort 函数按偶数或奇数对数字进行排序。
我有以下代码,但我不确定如何在 std::sort 中实现
inline bool isEven(const Point n) {
return n.getX()%2==0;
}
它是否正确
vector<Point> c;
std::sort(c.begin(),c.end(),isEven)
请指教。
根据我对你的问题的理解,你想分开odd
and even
数字。如果是这样的话,std::partition http://en.cppreference.com/w/cpp/algorithm/partition就会这么做。
如果您想按升序值排序并分开odd
and even
数字,我会使用类似于这段代码的东西(仍然,你必须弄清楚你的哪个组件Point
你想要排序)
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 http://en.cppreference.com/w/cpp/algorithm/sort,这是一个简短的示例:
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
范围
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)