Другие языки программирования и технологии

Как удалить нулевые элементы из массива C++. Помогите написать код для того чтобы из массива удалить все нулевые элементы

#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
void create_array(int *, const size_t, const int k = 10);
void show_array(int *, const size_t);
size_t newsize_array(int *, const size_t, const int);
int * change(int *, size_t &, const int del = 0);
int * delete_array(int *);
int main() {
    srand(unsigned(time(0)));
    locale::global(locale(""));
    size_t size = 15 + rand() % 20;
    int * a = new int [size];
    create_array(a, size);
    cout << "Исходный массив: " << endl;
    show_array(a, size);
    a = change(a, size);
    cout << "Изменённый массив: " << endl;
    show_array(a, size);
    a = delete_array(a);
    a = NULL;
    cin.get();
    return 0;
}
void create_array(int * a, const size_t size, const int k) {
    for (size_t n = 0; n < size; n++) a[n] = rand() % k;
}
void show_array(int * a, const size_t size) {
    for (size_t n = 0; n < size; n++) cout << a[n] << ' ';
    cout << endl;
}
size_t newsize_array(int * a, const size_t size, const int del) {
    size_t newsize = size;
    for (size_t n = 0 ; n < size; n++) if (a[n] == del) --newsize;
    return newsize;
}
int * change(int * a, size_t & size, const int del) {
    if (size_t newsize = newsize_array(a, size, del)) {
        int * temp = new int [newsize];
        size_t next = 0;
        for (size_t n = 0; n < size; n++) {
            if (a[n] == del) continue;
            temp[next++] = a[n];
        }
        delete_array(a);
        size = newsize;
        return temp;
    } else return a;
}
int * delete_array(int * a) {
    delete[] a;
    return a;
}
Данила Мастер
Данила Мастер
68 493
Лучший ответ
"Код" не пишут, а получают в результате компиляции исходного текста.
Писать не буду, но подскажу, что здесь лучше всего использовать вектор и метод erase.
http://ideone. com/wAen1r
Смотри 23 строку.

Если что - обращайся, всегда готов помочь за так или за плату, смотря что за задача.
Murat Ozturk
Murat Ozturk
2 769