c++ - 可以仅使用 std::sort() 将零移动到数组的末尾吗?

标签 c++ sorting stl

<分区>

我正在研究这个问题:

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

我知道如何通过就地交换来回答这个问题,但我也想看看是否可以使用 std::sort 来解决它。

根据 cplusplus.com:

the comparator function for the sort function is a Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.

The function shall not modify any of its arguments.

This can either be a function pointer or a function object.

//comments below are based on my understanding
static bool comp(int a, int b){
    //lambda function evaluates to true - no swap, 
    //evaluates to false -swap
    if(a==0) return false;
    if(b==0) return true;
    //if neither a nor b is 0 them do not swap
    return true;
}

void moveZeroes(vector<int>& nums) {
    sort(nums.begin(),nums.end(),comp);
}

给定的测试用例是[0,1,0,3,12]

我的输出是[12,3,1,0,0]

最佳答案

你几乎是对的。在比较器函数中,您必须返回 false 才能不交换它们。此外,将 std::sort 更改为 std::stable_sort以保持原始顺序的值。

static bool comp(int a, int b)
{
    //lambda function evaluates to true - no swap, 
    //evaluates to false -swap
    if(a==0) return false;
    if(b==0) return true;
    //if neither a nor b is 0 them do not swap
    return false;
}

void moveZeros(std::vector<int>& nums)
{
    std::stable_sort(nums.begin(),nums.end(),comp);
}

LIVE DEMO

关于c++ - 可以仅使用 std::sort() 将零移动到数组的末尾吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54318404/

相关文章:

c++ - TCP套接字服务器c++/c窗口大小

linux - 如何在 OSX 中执行 `sort -V`?

ios - iOS 上的 std::thread

c++ - 使用 GUID 作为 std::hash_map 中的键的 "right"方法是什么

c++ - 定义一个在全局范围内运行的宏,没有警告

c++ - 有没有好的C++模板引擎

c++ - 制作分组框按钮 win32 C++

sorting - 在自引用对象上覆盖compareTo(父/子关系)

java - Java中不排序的自定义对象数组排序

c++ - 将 OpenCv Mat 插入到 C++ std::vector