Sự Kết hợp hoàn hảo giữa c/c++ realloc +REALLOc+kiểu dữ liệu khuôn mẫu template trong việc xóa phần tử trong mãng con trỏ

#include<iostream> using namespace std; #include<stdio.h> #include<conio.h> #include<stdlib.h> // hàm xóa void xuat(int *a,int n) { for (int i = 0; i < n; i++) { cout << "\n " << a[i] << endl; } } /// thao tác với con trỏ thì ta cần tạo hàm realloc (giảm 1 vùng nhớ trên con trỏ) template<class chucdeptrai > void REALLOC(chucdeptrai *&a, int newsize, int oldsize) { chucdeptrai *tam = new int[oldsize];// đổ dữ liêu75 từ mãng củ qua for (int i = 0; i < oldsize; i++) { tam[i] = a[i]; } delete[] a; a = new int[newsize]; chucdeptrai min = newsize < oldsize ? newsize : oldsize;// phải âấy size nhỏ hơn tránh trường hợp rôi vào vùng nhớ không hợp lệ for (int i = 0; i < min; i++) { a[i] = tam[i]; } delete[] tam; } void xoa(int *&a,int &n,int pos) { for (int i=pos; i < n; i++) { a[i] = a[i + 1]; } n--; //REALLOC<int>(a, n, n + 1); realloc(a, n*sizeof(n)); } void xoale(int *&a, int &n) { for (int i = 0; i < n; i++) { if (a[i] % 2 != 0) { xoa(a, n, i); i--; //REALLOC(a, n - 1, n); } } } int main() { int n = 5; int *a = new int[n]{ 3,2,6,7,8 }; xoale(a, n); // realloc(a, n); xuat(a,n); //REALLOC(a, n + 2, n); //a[6] = 90; //a[7] = 80; //cout << a[6]<<":"<<a[7]; delete[] a; system("pause"); return 0; }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.