Hello! I have a working code for working with an array, but I want to implement it into a dynamic array.

#include <iostream> #define pause system("pause") using namespace std; int main() { setlocale(LC_ALL, "Russian"); const int n=10; int M[n]={45,35,32,62,64,13,6,14,265,1}; bool sort=true; int d,c; do { sort=false; for(int b=0; b < n-1; b++) { if(M[b] > M[b+1]) { sort=true; c=M[b]; M[b]=M[b+1]; M[b+1]=c; } } }while(sort == true); for(d=0; d < n; d++) cout << "Индекс массива " << d << " число: " << M[d] << "\n"; pause; } 

Please help me how it can be implemented. I am writing on VC ++ 2012.

  • and std::vector<int> cannot be used? - KoVadim
  • Replace the int * M [n] = {...} construct with sdt :: vector <int> M (n, 0). The rest of the code can be left unchanged. - vladimir_ki

1 answer 1

 #include <iostream> #define pause system("pause") using namespace std; int main() { setlocale(LC_ALL, "Russian"); int n; cin >> n; int* m = new int[n]; bool sort=true; int d,c; do { sort=false; for(int b=0; b < n-1; b++) { if(M[b] > M[b+1]) { sort=true; c=M[b]; M[b]=M[b+1]; M[b+1]=c; } } }while(sort == true); for(d=0; d < n; d++) cout << "Индекс массива " << d << " число: " << M[d] << "\n"; pause; 

}

I also advise you to read about vector just for the purposes that you need!

  • @Reocder And who will free the memory? - dzhioev
  • @Reocder And who will initialize the elements? - dzhioev
  • and how to free up memory? - Max Adamchuk
  • @Max Adamchuk, about how to free up memory, you can read in any book on C ++. - dzhioev
  • one
    > then why was this forum created? in order to help with what is not in the books! or what is not as simple as new / delete - ProkletyiPirat