书本411页。练习12.6:编写函数,返回一个动态分配的int的vector。将此vector传递给另一个函数,这个函数读取标准输入,将输入的值保存在vector元素中,再将vector传递给另一个函数,打印输入的值。记得在恰当的时候delete vector。
#include <iostream>
#include <vector>
using namespace std;
vector<int> *new_vector(void)
{
return new(nothrow) vector<int>;
}
void read_ints(vector<int> *pv)
{
int v;
while (cin >> v)
{
pv->push_back(v);
}
}
void print_ints(vector<int> *pv)
{
for (const auto &v : *pv)
cout << v << " ";
cout << endl;
}
int main(int argc, char *argv[])
{
vector<int> *pv = new_vector();
if (!pv)
{
cout << "内存不足" << endl;
return -1;
}
read_ints(pv);
print_ints(pv);
delete pv;
pv = nullptr;
}
12.7使用shared_ptr。非内置指针
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
shared_ptr<vector<int>> new_vector(void)
{
return make_shared<vector<int>>();
}
void read_ints(shared_ptr<vector<int>> spv)
{
int v;
while (cin >> v)
{
spv->push_back(v);
}
}
void print_ints(shared_ptr<vector<int>> spv)
{
for (const auto & c : *spv)
{
cout << c << " ";
}
cout << endl;
}
int main(int argc, char *argv[])
{
auto spv = new_vector();
read_ints(spv);
print_ints(spv);
return 0;
}
12.23连接两个字符串字面常量,将结果保存在一个动态的分配char数组中。#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
{
const char*c1 = "Hello ";
const char*c2 = "World";
char *r = new char[strlen(c1) + strlen(c2) + 1];
strcpy(r, c1);//拷贝
strcat(r, c2);//链接
cout << r << endl;
string s1 = "Hello ";
string s2 = "World";
strcpy(r, (s1 + s2).c_str());
cout << r << endl;
delete[]r;
return 0;
}
12.24从标准输入中读取一个字符串,存入一个动态分配的字符数组中。描述你的程序如何处理变长输入#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
{
char c;
char *r = new char[20];
int l = 0;
while (cin.get(c))
{
if (isspace(c))
break;
r[l++] = c;
if (l == 20)
{
cout << "容量大于上限" << endl;
break;
}
}
r[l] = 0;
cout << r << endl;
delete[]r;
return 0;
}