Frage

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.

War es hilfreich?

Lösung

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);

Andere Tipps

Operator == checks the equality, you must use = to assign.

memBlock[i-1] = memBlock[i];

Arrays in C++ have not any member like .length(). They are not classes.

for(int i=1; i <= 100; i++)
                  ^^^

If you know the size at compile-time, use std::array if available. Then you can do ".size()" :) Also, your code doesn't work if you have several consecutive zeroes. Every element is shifted to the left at most once, which is clearly insufficient to achieve your desired result. What you need to do is keep track of a separate "output" index/iterator which receives any non-zero value you encounter and is then incremented:

std::array<char, 100> aBlock;
aBlock[10] = 's';
aBlock[20] = 'a';
aBlock[30] = 'd';

auto output = aBlock.begin(); // or aBlock if you don't have std::array;
for (auto input = aBlock.begin(); input != aBlock.end(); ++input)
{
  if (*input != 0)
  {
    if (output != input)
    {
      *output = input;
      *input = 0;
    }
    ++output;
  }
}

That should do the trick.

int arrsize = 100;

...

int i, j;
for(i = 0, j = 0; i < arrsize ; i++) {
    if(memBlock[i] != 0 && i != j) {
        memBlock[j++] = memBlock[i];
        memBlock[i] = 0;
    }
}

Side note: new in global space? And where is delete[] ?

change

    memBlock[i-1] == memBlock[i];

to

    memBlock[i-1] = memBlock[i];

"==" is the problem i think.

use

     if(aBlock[i-1] != 0)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top