c++arraysshuffleshift

c++ shift array elements to left


I've only recently taken up C++ and am having difficulty shifting array elements to remove empty/null elements

char *aBlock;
aBlock = new char[100];

int main(int argc, char **argv)
{
aBlock[20] = 'a'; // fill array with test data.
aBlock[10] = 's';
aBlock[30] = 'd'; // Excepted output: This test data should be shifted to the start of array

// Consider aBlock contains data, with random empty elements
    for(int i=1; i <= aBlock.length(); i++) {
        if(aBlock[i-1] == 0) {
            aBlock[i-1] = aBlock[i];
            aBlock[i] = 0;
        }
    }

    return 0;
}

Edit: Fixed a code typo & wrong variable names, changed "==" to "=". It still doesn't work as expected.


Solution

  • If I understood correctly, you want to move the non-zero elements at the beginning of your array. You could use std::remove_if to do this and set the rest of the elements to 0.

    std::fill(
       std::remove_if(std::begin(aBlock), std::end(aBlock), [](char const c) {return c == '\0'; }),
       std::end(aBlock),
       0);
    

    UPDATE:

    Since the array is dynamically allocated you need a small change:

    std::fill(
       std::remove_if(&aBlock[0], &aBlock[100], [](char const c) {return c == '\0'; }),
       &aBlock[100],
       0);