Good C++ solutions to the “Bring all the zeros to the back of the array” interview challenge

前端 未结 3 1194
面向向阳花
面向向阳花 2021-01-01 01:43

I had an interview for a Jr. development job and he asked me to write a procedure that takes an array of ints and shoves the zeroes to the back. Here are the constraints (wh

3条回答
  •  余生分开走
    2021-01-01 02:31

    Maybe the interviewer was looking for this answer:

    #include 
    //...
    std::partition(std::begin(arr), std::end(arr), [](int n) { return n != 0; });
    

    If the order needs to be preserved, then std::stable_partition should be used:

    #include 
    //...
    std::stable_partition(std::begin(arr), std::end(arr), [](int n) { return n != 0; });
    

    For pre C++11:

    #include 
    #include 
    //...
    std::partition(arr, arr + sizeof(arr)/sizeof(int), 
                   std::bind1st(std::not_equal_to(), 0));
    

    Live Example

    Basically, if the situation is that you need to move items that satisfy a condition to "one side" of a container, then the partition algorithm functions should be high up on the list of solutions to choose (if not the solution to use).

提交回复
热议问题