C++容器作为函数形参进行使用
如这个编程题:
该题是对容器的简单应用,由于数组在定义的时候要么用列表初始化间接告诉编译器数组的大小,要么在定义的时候直接定义它的大小如:int arry[100],不仅浪费空间,还让人感到特别的死板。而容器在这方面做到了动态存储的感觉。vectorivec直接可用其成员函数ivec.push_back(i)来输入元素而不需要下标访问的形势来存储元素。
我的代码如下:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
struct StuInfor
{
int num;
string name;
double height;
};
void Read(vector<StuInfor>&stu, int n)
{
cout << "请依次输入学生的学号、姓名、和身高:" << endl;
for (int i = 0; i != n; ++i)
{
cin >> stu[i].num;
cin >> stu[i].name;
cin >> stu[i].height;
}
}
StuInfor FindHi(vector<StuInfor>stu, int n)
{
int flag1 = 0;
double highest = 0;
for (int i = 0; i != n; ++i)
{
if (highest < stu[i].height) {
highest = stu[i].height;
flag1 = i;
}
if (highest == stu[i].height && stu[flag1].num > stu[i].num) {
flag1 = i;
}
}
return stu[flag1];
}
int main()
{
int n;
StuInfor s;
cout << "请输入学生人数:" << endl;
cin >> n;
vector<StuInfor>stu(n);
Read(stu, n);
s = FindHi(stu, n);
cout << "最高的学生信息如下:" << endl;
cout << "学号:" << s.num << endl;
cout << "姓名:" << s.name << endl;
cout << "身高:" << s.height <<"cm"<<endl;
return 0;
}
特别注意在Read函数里面的容器形参是引用,如同经典的C语言的swap交换两个值的函数,若直接穿入容器,实参的值依旧是默认初始化的值,而若用引用就可在函数内部直接改变main函数中容器的元素。
A、若函数不是引用类型,输出结果为:
B、若为引用:
所以在使用容器作为函数形参时尽量使用引用类型。