<C++ Primer_5th>习题_3.31

//编写一个程序,定义一个含有10个int的数组,令每个元素的值就是其所在位置的值

#include<iostream>

using namespace std;

int main()
{
	const int sz = 10;
	int a[sz];
	//遍历数组元素并赋值
	for (int i = 0; i < sz; ++i)
	{
		a[i] = i;
	}
	//输出数组中的全部元素
	cout << "数组中的元素依次为:";
	for (auto c : a)
	{
		cout <<c << "  ";
	}
		
	cout << endl;
	system("pause");
	return 0;
}

//将上面创建的数组拷贝给另外一个数组。利用vector重写程序,实现类似功能

//利用数组来拷贝

#include<iostream>

using namespace std;

int main()
{
	const int sz = 10;
	int a[sz], b[sz];
	//利用for循环为数组赋值
	for (int i = 0; i < sz; ++i)
		a[i] = i;
	for (int j = 0; j < sz; ++j)
		b[j] = a[j];
	//利用范围for循环输出数组的全部元素
	cout << "数组中的元素依次为: ";
	for (auto c : b)
		cout << c << "  ";
	cout << endl;
	system("pause");
	return 0;
}

//利用vector实现拷贝

#include<iostream>
#include<vector>	

using namespace std;

int main()
{
	const int sz = 10;
	vector<int> v_int, v_int2;
	for (int i = 0; i < sz; ++i)
		v_int.push_back(i);
	for (int j = 0; j < sz; ++j)
		v_int2.push_back(v_int[j]);
	//输出vector对象中的元素
	cout << "输出的元素依次为: ";
	for (auto c : v_int2)
		cout << c << "  ";
	cout << endl;
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值