1 vector类模板:容纳任何类型的容器
定义
vector可以封装任何类型的动态数组,自动创建和删除
数组下标越界检查
定义:
vector<元素类型> 数组对象名(数组长度);
例:
vector arr(5),建立大小为5的int数组,(动态分配内存,自动删除,越界检查)
实例
1
2
3vector<double> arr(n); //创建元素个数为n的数组对象 vector<int> v = {1, 2, 3}; //创建
这条语句生成一个类,专门用来存放double类型的元素,定义一个对象arr,对象内嵌了一个数组,这个数组有n个元素。 (这个过程相当于5.30文章最后一段代码的过程:生成一个ArrayOfPoints类,专门用来存放int类型的元素,定义一个对象aaa,对象内嵌了一个数组,数组有size个元素,指针points指向该数组)
1.double average(const vector< double>& aaa) 形参是vector< double>类型的数据,类似const int& a这种普通变量的传递,传递“只读”引用。注意不能写成double*,只能写成vector<>类型。
2.aaa虽然在主函数中可以用下标,但aaa是一个类的对象,是一个vector容器的实例,不能当类似数组作为指向首元素指针使用,即不能使用*aaa等操作
size()函数直接读取数组元素个数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25#include <iostream> #include <vector> //注意// using namespace std; //计算数组arr中元素的平均值 double average(const vector<double>& aaa) //vector<double>类型的数据,类似const int& a普通变量的传递 { //有size()函数,无需传数组个数过来 double sum = 0; for (unsigned i = 0; i < aaa.size(); i++) sum += aaa[i]; return sum / aaa.size(); } int main() { unsigned n; cout << "n = "; cin >> n; vector<double> arr(n); //创建数组对象 cout << "Please input " << n << " real numbers:" << endl; for (unsigned i = 0; i < n; i++) cin >> arr[i]; //可以用数组名下标的方式来访问每一个元素。 cout << "Average = " << average(arr) << endl; return 0; }
vector里重载了下标运算符,所以与ArrayOfPoints类不能使用下标不同,可以使用下标。把这个vector对象的**“只读”、“引用”**传递给average函数
2 基于范围的for循环配合auto
1
2
3
4
5
6
7
8
9
10
11
12#include <vector> #include <iostream> int main() { std::vector<int> v = { 1,2,3 }; for (auto i = v.begin(); i != v.end(); ++i) std::cout << *i << std::endl; for (auto e : v) std::cout << e<< std::endl; return 0; }
3 传递普通变量的引用、传递数组的引用
普通变量,加const表示只读值
1
2
3
4
5
6
7void fun1(const int& a){ a += 4; //error,a不可修改 } int main(){ int b = 5; fun1(b);}
指针就是一个可以代表数组的东西,数组相关的操作传递指针即可,用*来使用数组的值
传递数组的引用,传递数组名或指向首地址的指针均可,const表示不能通过该指针来修改数组的值。
1
2
3
4
5
6
7
8void fun2(const int* a){ cout << *(a+1) + 3 <<endl; //输出5 } int main(){ int array[2] = {1, 2}; fun2(array); }
最后
以上就是大气山水最近收集整理的关于5.31C++:vector、基于范围的for循环配合auto、传递引用;vector对象名不能当做数组的头指针使用1 vector类模板:容纳任何类型的容器2 基于范围的for循环配合auto3 传递普通变量的引用、传递数组的引用的全部内容,更多相关5.31C++:vector、基于范围的for循环配合auto、传递引用;vector对象名不能当做数组的头指针使用1内容请搜索靠谱客的其他文章。
发表评论 取消回复