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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章