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
- 12.2节练习
- 第十二章 12.2.2节练习 & 12.3.1节练习
- C++ Primer 练习答案 1.2节练习
- C++ Primer 练习答案 1.4节练习
- 12.2C语言练习
- 第一章 1.1节练习
- 第一章 1.2节练习
- 第一章 1.3节练习
- 10.1节练习
- 10.2.1节练习
- 10.2.2节练习
- 10.2.3节练习
- 10.3.1节练习
- 10.3.2 节练习
- 10.3.3节练习
- 10.3.4节练习
- 10.4.1节练习
- 10.4.2 节练习
- Lua面向对象之类和继承浅析
- java8中switch(String)的错误解决
- 计算机组成简易说明
- ubuntu 16.04 amd64位系统安装QT5.6
- 电信三户模型
- 12.2节练习
- php导入大量数据到mysql性能优化技巧
- Lua面向对象之类和继承
- 排序算法-快速排序(入门)
- 论文写作技巧----页码设置
- 如何修改MySQL数据库单表的引擎
- hdu 2119 Matrix【最小点覆盖-二分匹配】
- 论文写作技巧----分隔符
- 关系数据库和Hbse