C++学习笔记七之使用数组区间的函数
2017-07-10 12:21
706 查看
前面已经学习过求一个数组的总和,现在我要求数组中的一个区间的值的和,假设我要求第2个元素到第6个元素的和,只能连续。这里就需要有一个函数来进行求和,指定一个初始位置和一个结束位置,然后求得初始位置到结束位置的值的和。这里有两种方法求解,一种是用指针来指向数组的起始位置和结束位置;另一种是用数组的下标来代表数组的起始位置和结束位置。
首先要知道数组名其实就是一个指针,它指向的是数组的起始位置,arr=&arr[0];
【示例代码】
【演示结果】
首先要知道数组名其实就是一个指针,它指向的是数组的起始位置,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的值的和。
【演示结果】
相关文章推荐
- C++学习笔记六之函数如何使用指针来处理数组?
- c++学习笔记(一):函数指针的使用
- C++学习笔记四之使用new来创建动态数组
- PHP学习笔记——使用回调函数处理数组函数array_map()
- 【C++】vector容器和list容器中使用单个迭代器的erase函数学习笔记
- 【C++学习笔记】使用控制符及流对象的成员函数控制输出格式
- C++学习笔记8,const在函数方面的使用(二)
- PHP学习笔记——使用回调函数处理数组的函数array_filter()
- C++学习笔记-函数数组传参
- PHP学习笔记——使用数组的内部指针控制函数遍历数组
- c++学习笔记(七):函数返回数组
- PHP学习笔记——使用回调函数处理数组的函数array_walk()
- C++学习笔记(三)--函数参数,数组函数,指针和const,二维数组函数,递归,函数指针
- C++学习笔记(八):对字符的操作函数和范围for语句的使用
- C/C++学习笔记12:数组作为函数参数
- c++ 模板学习笔记:函数模板实现数组通用排序和遍历打印(权哥)
- Effective C++学习笔记 条款06:如不想使用编译器自动生成的函数,就该明确拒绝
- C++学习笔记之函数如何返回字符串(char型)
- c++学习笔记--虚函数和多态的重新认识
- 一个无聊男人的疯狂《数据结构与算法分析-C++描述》学习笔记 习题2.8 随机数组的三种生成算法(补) 将bash的实现翻译成比较纯正的bash风格