vector c++元素做函数参数怎么弄

最近碰到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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超自然祈祷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值