C++学习笔记七之使用数组区间的函数

来源:互联网 发布:mac怎样整理文件 编辑:程序博客网 时间:2024/05/22 06:58

前面已经学习过求一个数组的总和,现在我要求数组中的一个区间的值的和,假设我要求第2个元素到第6个元素的和,只能连续。这里就需要有一个函数来进行求和,指定一个初始位置和一个结束位置,然后求得初始位置到结束位置的值的和。这里有两种方法求解,一种是用指针来指向数组的起始位置和结束位置;另一种是用数组的下标来代表数组的起始位置和结束位置。

首先要知道数组名其实就是一个指针,它指向的是数组的起始位置,arr=&arr[0];

【示例代码】

#include <iostream>#include <stdlib.h>const int ArSize = 8;int sum_arr(const int *begin,const int *end);int sum_love(int cook[],const int begin,const int end);int main(){using namespace std;int cook [ArSize]= {1,2,3,4,5,6,7,8};int sum = sum_arr(cook,cook+ ArSize);//数组名代表第一个元素的地址cout << "Total cook eaten: " << sum << endl;sum = sum_arr(cook, cook + 3);cout << "First three eaters ate "<<sum<<" cook.\n";sum = sum_arr(cook+4, cook+8);cout << "Last four eaters ate " << sum << " cook.\n";//直接用数组名int sum1 = sum_love(cook,0,8);cout << "cook: " << cook<<endl;cout << "输出前三个值的和:"<<sum1<<endl;system("pause");return 0;}int sum_arr(const int *begin,const int *end){using namespace std;const int *pt;int total = 0;for (pt=begin;pt!=end;pt++){total = total + *pt;}cout << "begin: " << begin << "\t" << endl;return total;}int sum_love(int cook[],const int begin,const int end){using namespace std;int total = 0;for (size_t i = begin; i<end; i++){total = total+cook[i];}return total;}
【代码解析】

int sum_arr(const int *begin,const int *end){using namespace std;const int *pt;int total = 0;for (pt=begin;pt!=end;pt++){total = total + *pt;}cout << "begin: " << begin << "\t" << endl;return total;}
这里一开始的参数是两个指针,分别指向数组区间的起始位置begin和结束位置end。然后定义了一个int类型的指针pt,进入for循环中,把传入的begin(也就是区间起始地址)赋给了pt作为for循环的起始值,开始遍历求和,直到等于end,循环结束。

int sum = sum_arr(cook,cook+ ArSize);//数组名代表第一个元素的地址
注意:这里的cook+ArSize是指向数组的结束位置的下一个位置,所以cook+(ArSize-1)才是数组的结束位置。假设begin=0;end=5;上面for循环求和求的是前5个值的和,也就是0到4的值的和。

【演示结果】






阅读全文
0 0
原创粉丝点击