<C++ Primer_5th>习题_3.36

//编写一段程序,比较两个数组是否相等

#include<iostream>
#include<ctime>
#include<cstdlib>

using namespace std;

int main()
{
	const int sz = 5;
	int a[sz], b[sz], i;
	//生成随机数种子
	srand((unsigned)time(NULL));
	//为数组赋值
	for (i = 0; i < sz; ++i)
		//每次循环生成一个10以内的随机数并添加到a中
		a[i] = rand() % 10;
	cout << "系统数据已经生成,请输入您猜测的5个数字(0~9),可以重复: " << endl;
	int uVal;
	//为数组赋值
	for (i = 0; i < sz; ++i)
		if (cin >> uVal)
			b[i] = uVal;
	//输出
	cout << "系统生成的数据是: ";
	for (auto c : a)
		cout << c << "  ";
	cout << endl;
	cout << "您猜测的数据是: ";
	for (auto c : b)
		cout << c << "  ";
	cout << endl;
	//比较2个数组
	int *p = begin(a), *q = begin(b);
	while (p != end(a) && q != end(b))
	{
		if (*p != *q)
			cout << "您的猜测错误,两个数组不相等" << endl;
		system("pause");
		return -1;
	}
	++p;
	++q;
	system("pause");
	return 0;
}

//使用迭代器对比两个vector对象是否相等

#include<iostream>
#include<vector>
#include<ctime>
#include<cstdlib>

using namespace std;

int main()
{
	const int sz = 5;
	vector<int> a, b;
	int i;
	//生成随机数种子
	srand((unsigned)time(NULL));
	//为数组元素赋值
	for (i = 0; i < sz; ++i)
		//每次循环生成一个10以内的随机数并添加到a中
		a.push_back(rand() % 10);
	cout << "系统数据已经生成,请输入您猜测的5个数字(0~9),可以重复: " << endl;
	int uVal;
	//为数组元素赋值
	for (i = 0; i < sz; ++i)
		if (cin >> uVal)
			b.push_back(uVal);
	cout << "系统生成的数据是: " << endl;
	for (auto c : a)
		cout << c << " ";
	cout << endl;
	//输出
	cout << "您猜测的数据是: " << endl;
	for (auto c : b)
		cout << c << "  ";
	cout << endl;
	//比较2个vector对象
	auto it1 = a.cbegin(), it2 = b.cbegin();
	//auto it1 = a.cend(), it2 = b.cend();
	while (it1 != a.cend() && it2 != b.end())
	{
		if (*it1 != *it2)
		{
			cout << "您的猜测错误,两个vector对象不相等" << endl;
			system("pause");
			return -1;
		}
		++it1;
		++it2;
	}
	cout << "恭喜您全都猜对了!" << endl;
	system("pause");
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值