new-del.cpp - Illustration of free store. | Lecture 2 - slide 34 : 46 Program 1 |
#include <iostream> #include <iomanip> #include <string> #include <vector> using namespace std; int main(){ // An int: int *pi = new int; // Allocate an int *pi = 5; cout << 6 * *pi << endl; // 30 delete pi; // Deallocate the int // An array of int: int *ia = new int[10]; // Allocate an array of 10 ints for(int i = 0; i < 10; i++) // Initialize array ia[i] = 2 * i; for(int i = 0; i < 10; i++) cout << setw(3) << ia[i]; // 0 2 4 6 8 10 12 14 16 18 cout << endl; delete [] ia; // Deallocate the array // A vector of ints: vector<int> *vd = new vector<int>(10); // Allocate a vector for(int i = 0; i < 5; i++) // Mutate half of the vecctor (*vd)[i] = 2 * i; for(int i = 0; i < 10; i++) cout << setw(3) << (*vd)[i]; // 0 2 4 6 8 0 0 0 0 0 cout << endl; delete vd; // Deallocate the vector }