12.2节练习

来源:互联网 发布:c语言时间转时间戳 编辑:程序博客网 时间:2024/06/06 03:14

练习12.23 编写一个程序,连接两个字符串字面常量,将结果保存在一个动态分配的char数组中。重写这个程序,连接两个标准库string对象。

#include <iostream>#include <memory>#include <string>using namespace std;int main(){//情况一char c1[] = "world";char c2[20] = "hello ";strcat_s(c2, sizeof(c2),c1); //使用strcat编译不通过,只好用更安全的函数cout << c2 << endl;//情况二string s1 = "C++ ";string s2 = "Primer";string s3 = s1 + s2;string *p = new string[s3.size()];for (auto i = 0; i != s3.size(); ++i) {*(p + i) = s3[i];}for (auto i = 0; i != s3.size(); ++i) {cout << *(p + i);}delete[]p;cout << endl;}


12.24 编写一个程序,从标准输入读取以个字符串,存入一个动态分配的字符数组中。描述你的程序如何处理变长输入。测试你的程序,输入一个超出你分配的数组长度的字符串。

#include <iostream>#include <string>#include <memory>using namespace std;int main(){string s;cin >> s;char *p = new char[2];for (size_t i = 0; i < s.size(); ++i) {*(p+i) = s[i];}for (size_t i = 0; i < s.size(); ++i) {cout << *(p+i);}delete[]p;}
创建动态数组由new返回的是一个元素类型指针,当试图输入一个超出你分配的数组长度的字符串,原以为会自动分配内存以保存超出的部分,然而现实是程序报错。


练习12.25 给定下面的new表达式,你应该如何释放pa?

int *pa = new int[10];delete[]pa;}

练习12.26 用allocator重写第427页中的程序。

#include <iostream>#include <string>#include <new>#include <memory>using namespace std;int main(){allocator<string> alloc;auto p = alloc.allocate(10);auto q = p;auto pi = p;string s;while (cin >> s && q != p + 10) {alloc.construct(q++, s);}//输出while (q != p) {cout << *p++ << " ";}//对真正进行构造的元素进行销毁while (pi != p) {alloc.destroy(--p);}alloc.deallocate(pi, 10);return 0;}


0 0