练习3.32
数组实现
#include<iostream>
#include<string>
using namespace std;
int main()
{
const int sz=10;
int ia[sz],ib[sz];
for (int i = 0; i < 10; i++)
ia[i] = i;
for (int j=0; j < 10; j++)//不能直接对数组使用复制运算符,需要逐一拷贝
ib[j] = ia[j];
for (auto val : ib)
cout << val << " ";
return 0;
}
vector实现
#include<iostream>
#include<vector>
using namespace std;
int main() {
const int sz=10;
vector<int>v1, v2;
for (int i = 0; i < sz; i++)
v1.push_back(i);
for (int j = 0; j < sz; j++)
v2.push_back(v1[j]);
for (auto val : v2)
cout << val << " ";
cout << endl;
return 0;
system("pause");
}
练习3.35:编写一段程序,利用指针将数组中的元素置为0。
#include<iostream>
#include<string>
using namespace std;
int main()
{
const int sz = 10;
int a[sz], i = 0;
for (i = 0; i < sz; i++)
a[i] = i;
int *p = begin(a);//令p指向a的首地址
while (p != end(a))
{
*p = 0;
p++;
}
for (auto val : a)
cout << val << " ";
return 0;
}
练习3.36:编写一段程序,比较两个数组是否相等。再写一段程序,比较两个vector对象是否相等。
【出题思路】
无论对比两个数组是否相等还是两个vector对象是否相等,都必须逐一比较其元素。
【解答】
对比两个数组是否相等的程序如下所示,因为长度不等的数组一定不相等,并且数组的维度一开始就要确定,所以为了简化起见,程序中设定两个待比较的数组维度一致,仅比较对应的元素是否相等。
该例类似于一个彩票游戏,先由程序随机选出5个0~9的数字,此过程类似于摇奖;再由用户手动输入5个猜测的数字,类似于购买彩票;分别把两组数字存入数组a和b,然后逐一比对两个数组的元素;一旦有数字不一致,则告知用户猜测错误,只有当两个数组的所有元素都相等时,判定数组相等,即用户猜测正确。
数组实现
#include<iostream>
#include<string>
#include<ctime>
//#include<vector>
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++)
a[i] = rand() % 10;
cout << "请输入猜测的5个数字" << endl;
int val;
for (i = 0; i < sz; i++)
if (cin >> val)
b[i] = val;
cout << "随机数字是:" << endl;
for (auto x : a)
cout << x << " ";
cout << "你猜的是:" << endl;
for (auto x : b)
cout << x << " ";
cout << endl;
int *p = begin(a), *q = begin(b);
while (p != end(a) && q != end(b))
{
if (*p != *q)
{
cout << "you are wrong" << endl;
return -1;
}
p++;
q++;
}
return 0;
}
vector实现
#include<iostream>
#include<string>
#include<ctime>
#include<vector>
#include<cstdlib>
using namespace std;
int main()
{
const int sz = 5;
vector<int>v1, v2;
srand((unsigned)time(NULL));
for (int i = 0; i < sz; i++)
v1.push_back(rand() % 10);
cout << "请输入猜测的5个数字" << endl;
int val;
for (int i = 0; i < sz; i++)
if (cin >> val)
v2.push_back(val);
cout << "随机数字是:" << endl;
for (auto x : v1)
cout << x << " ";
cout << "你猜的是:" << endl;
for (auto x : v2)
cout << x << " ";
cout << endl;
auto it1 = v1.cbegin(), it2 = v2.cbegin();
while (it1 != v1.cend() && it2 !=v2.cend())
{
if (*it1 != *it2)
{
cout << "you are wrong" << endl;
return -1;
}
it1++;
it2++;
}
return 0;
}
练习3.40:编写一段程序,定义两个字符数组并用字符串字面值初始化它们;接着再定义一个字符数组存放前两个数组连接后的结果。使用strcpy和strcat把前两个数组的内容拷贝到第三个数组中。
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
const char str1[] = "Welcome to ";
const char str2[] = "C++ family ";
//利用strlen函数计算两个字符串的长度,并求结果字符串的长度
char ret[strlen(str1) + strlen(str2) - 1];
strcpy(ret, str1);
strcat(ret, str2);
cout << ret << endl;
return 0;
}
但是函数编译的时候会出现错误,不知道怎么回事