c++ primer 学习笔记11--动态内存

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










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值