数据结构、算法与应用(c++语言描述)
第一章
书上练习题 p6-p7
1、解释为什么程序1-7的交换函数没有把形参x和y所对应的实参进行交换。如何修改代码,使实参的值得到交换?
下面是程序1-7 交换两个整数的不正确的代码。
void swap(int x, int y){
// 交换整数x和y
int temp = x;
x = y;
y = temp;
}
下面是修改后的代码
#include <iostream>
using namespace std;
// 传递参数使用引用传递
void swap(int& a, int& b){
int tmep = a;
a = b;
b = tmep;
}
int main(){
int a = 1, b = 2;
swap(a, b);
cout << "a:" << a << "b:" << b << endl;
}
2、编写一个模板函数count,返回值是数组a[0: n-1]中出现的次数。测试你的代码。
#include <iostream>
using namespace std;
template <class type,int len>
int countValue(type array[len], type value)
{
int cnt = 0;
for (int i = 0; i < len; i++){
if (array[i] == value){
cnt += 1;
}
}
return cnt;
}
int main()
{
int array[5] = {
1,2,3,5,5};
cout << countValue<int,5>(array, 5) << endl ;
double array2[5] = {
1.2, 1.2, 1.3, 1.4, 1.5};
cout << countValue<double,5>(array2, 1.2);
}
测试结果:
2
2
3、编写一个模板函数fill,给数组a[start: end-1]复制value。测试你的代码。
#include <iostream>
using namespace std;
template