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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_27382047/article/details/83065858

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

猜你喜欢

转载自blog.csdn.net/sinat_27382047/article/details/83065858