1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include <algorithm>
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
string * copy(const string a[], unsigned els);
void show(const string a[], unsigned els);
bool die(const string & msg);
void grow(string * & a, unsigned oldEls, unsigned newEls);
int main() {
string a[] = { "Manny", "Moe", "Jack" };
string * b = copy(a, 3);
a[0] = "MANNY";
show(a, 3);
show(b, 3);
grow(b, 3, 5);
b[3] = "Russell";
b[4] = "Terrier";
show(b, 5);
string * ptr = NULL;
grow(ptr, 0, 4);
ptr[0] = "Doc", ptr[1] = "Sleepy", ptr[2] = "Dopey",
ptr[3] = "Happy";
grow(ptr, 4, 5);
ptr[4] = "Grumpy";
show(ptr, 5);
grow(ptr, 5, 2);
show(ptr, 2);
delete[] b;
cout << "bye" << endl;
}
string * copy(const string a[], unsigned els) {
string * ret = NULL;
try {
ret = new string[els];
}
catch (const bad_alloc &) {
die("allocation failure");
}
for (unsigned i = 0; i < els; i++)
ret[i] = a[i];
return ret;
}
void show(const string a[], unsigned els) {
for (unsigned i = 0; i < els; i++)
cout << "[" << i << "]: \"" << a[i] << "\"" << endl;
}
void grow(string * & a, unsigned oldEls, unsigned newEls) {
if (a == NULL && oldEls > 0) die("grow: inconsisent size");
string * newA = NULL;
try {
newA = new string[newEls];
}
catch (const bad_alloc &) {
die("allocation failure");
}
for (unsigned i = 0, lim = min(oldEls, newEls); i < lim; i++)
newA[i] = a[i];
delete[] a;
a = newA;
}
bool die(const string & msg) {
cout << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
|