I want to remove all the elements that are zero from an integer array. If I understand correctly that is "impossible" to do on the original array since it MUST have five elements after the declaration? Therefore I have to use another array c? :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//OBS the code works!
int b[5] = {0, 1, 0, 2, 3}; //For example
int numOfNoneZero = 0;
for(int i=0; i < 5; i++){
if(b[i] != 0)
numOfNoneZero++;
}
int c[numOfNoneZero];
int j = 0;
for(int i=0; i < 5; i++){
if(b[i] != 0)
c[j++] = b[i];
}
for(int i= 0; i < numOfNoneZero; i++)
cout << c[i] << endl;
delete[] b;
At the end I delete b. Is that enough to free the memory? But b still exists in some way? What if I want to completely destroy b for all eternity?
Are there any pre-written routines in C++ that could have done the work for me?
You do destroy b*. The memory to which it points is removed. You can't just obliterate a stack-allocated variable, though. It would have to go out of scope like this.
1 2 3 4 5
{
a variable is declared here;
}
but it no longer exists here
even if the code block has no connected statements like ifs
You would be better off using an STL container like a vector.
Thanks for the help guys, it does clear things. But I've realized I need a book after all. This is not as easy as I hoped :). Trying to translate a matlab code to C++. And in matlab the line a(a==0)=[]; would have been enough (not saying matlab is better obv).
Yeah, matlab is (kind of obviously) made for math stuff like matrices, arrays, and stuff like that. C++ has a bias towards systems programming, so it contains things like pointers, strings, etc.