Exercise 4.34: Write a program to read strings into a vector. Now, copy that vector into an array of character pointers. For each element in the vector, allocate a new character array and copy the data from the vector element into that character array. Then insert a pointer to the character array into the array of character pointers.
Exercise 4.35: Print the contents of the vector and the array created in the previous exercise. After printing the array, remember to delete the character arrays.
/* C++ Primer 习题 4.34 - 4.35 * By Ceeji */ #include <iostream> #include <vector> #include <string> using namespace std; typedef vector<string> vector_str; int main() { string str; vector_str strlist = vector_str(); while (getline (cin, str)) { strlist.push_back (str); } // 复制 strlist (vector) 中的数据到 字符指针数组中。 char **sz = new char*[strlist.size ()]; vector_str::iterator iter = strlist.begin (); int j = 0; while (iter != strlist.end()) { char * tmp = new char[(*iter).length ()+1]; for (int i = 0; i<(*iter).length (); i++) *(tmp + i) = (*iter).at (i); *(tmp + (*(iter++)).length ()) = NULL; *(sz + j++) = tmp; } for (int i = 0; i<strlist.size(); i++) { cout << *(sz + i) << endl; delete [] *(sz + i); } delete [] sz; return 0; } |