最近碰到vector有点懵,猛地想不出怎么只传一个元素……联想到结构体数组结果更乱了……
下面对比一下:
数组元素,定义函数参数是int
容器类,定义函数参数就是包含的结构体student
对于int型数组的元素作函数参数:
#include <iostream>
using namespace std;
void fun1(int num)//把数组的特定元素作为参数
{
cout <<"数组元素:" <<num << endl;//
}
int main()
{
int b[2] = { 1,2 };
fun1(b[0]);//对数组元素值的操作
return 0;
}
对于student结构体的数组的元素作函数参数:
#include <iostream>
using namespace std;
typedef struct
{
int x;
int y;
}student;
student mark[1];//student类型结构体数组
void fun2(student mum)//直接把结构体数组的元素作为参数
{
cout <<"student结构体,x:" << mum.x << endl;
cout <<"student结构体,y:" << mum.y << endl;
}
int main()
{
mark[0].x = 1;
mark[0].y = 1;
fun2(mark[0]);//传入结构体数组的元素(其实就是mark结构体)
return 0;
}
对于student结构体的容器的元素作函数参数:
#include <iostream>
#include <vector>
using namespace std;
typedef struct
{
int x;
int y;
}student;
vector<student> mark;//容器包含student结构体,然后定义了mark同学队列……
//void fun3(vector<student> num),过去这么想错误,就如同上例传整个数组void fun1(int num[])一样……
void fun3(student mum)//直接把对象的特定元素作为参数
{
cout <<"student结构体,x:" << mum.x << endl;
cout <<"student结构体,y:" << mum.y << endl;
}
int main()
{
mark.resize(1);//设置容量,否则会出现越界错误
mark[0].x = 1;
mark[0].y = 1;
fun3(mark[0]);//对象元素[0]的操作:就像结构体数组,访问其中一个元素一样
return 0;
}
下面是对比===============================================================
传数组和传数组元素的对比
#include<iostream>
using namespace std;
//声明
void f1(int a[]);
void f2(int a);
int main()
{
int a[1] = { 0 };//定义数组名叫a,内有1个元素,首元素是a[0]
//调用
f1(a);
f2(a[0]);
return 0;
}
//定义
void f1(int a[]) //传整个数组
{
cout << a[0] << endl;
}
void f2(int a) //传一个元素
{
cout << a << endl;
}
上一个简单的例子:数组元素、数组首地址做参数,还融合了数组第一位是0的知识点
#include<stdio.h>
void f1(int a)
{
printf("%d \n", a);
}
void f2(int a[])
{
printf("%d \n", a[2]);
}
void main()
{
int a[5] = { 1,2,3,4,5 };
f1(a[1]);
f2(a);
}
其运行结果是:2 换行 3
容器类:传“数组”和传“数组元素”的对比
#include <iostream>
#include <vector>
using namespace std;
typedef struct
{
int x;
int y;
}student;
vector<student> mark;//容器包含student结构体,然后定义了mark同学队列……
void fun4(vector<student> num)//如同传整个数组void fun1(int num[])
{
cout << "student结构体,x:" << num[0].x << endl;
cout << "student结构体,y:" << num[0].y << endl;
}
void fun3(student mum)//直接把对象的特定元素作为参数
{
cout << "student结构体,x:" << mum.x << endl;
cout << "student结构体,y:" << mum.y << endl;
}
int main()
{
mark.resize(1);//设置容量,否则会出现越界错误
mark[0].x = 1;
mark[0].y = 1;
fun3(mark[0]);//对象元素[0]的操作:就像结构体数组,访问其中一个元素一样
fun4(mark);//就像数组,传递数组名(首地址)一样
return 0;
}