C++笔记:习题 4.34 - 4.35

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;
}

题外话:我帮你整理了包括 AI 写作、绘画、视频(自媒体制作)零门槛 AI 课程 + 国内可直接顺畅使用的软件。想让自己快速用上 AI 工具来降本增效,辅助工作和生活?限时报名

当前页阅读量为: