<C++ Primer_5th>习题_3.36

来源:互联网 发布:方舟生存进化画面优化 编辑:程序博客网 时间:2024/06/05 15:32
//编写一段程序,比较两个数组是否相等#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;}