Using vectors in functions

May 21, 2012 at 3:22pm
[I am converting some array using college exercises to use vectors, but I need some help.]

I need to know how to use a vector in calling a function originally written using an array. If someone could show me some examples (my prototypes seem okay, but my calls are conflicted: "cannot convert parameter 1 from 'studentType [20]' to 'std::vector<_Ty>'"
1
2
3
4
5
6
7
8
9
10
/*Prototype*/void fnReadData(std::ifstream&, std::vector<studentType>, int);

/*Call*/fnReadData(ReadFile, students, 20);

/*Definition*/void fnReadData(ifstream &inFile, std::vector<studentType> sTy, int nArraySize) {
	while (inFile) {
		for (int i = 0; i < nArraySize; i++)
		inFile >> sTy[i].stStudentFName >> sTy[i].stStudentLName >> sTy[i].nTestScore;
	}
}


Again, examples would be very helpful.

Thank you, ERandall
May 21, 2012 at 3:28pm
If you want to modify the vector in the function, you need to pass it in as an reference or a pointer (reference makes more sense in this case). Also you need to make sure that the vector actually has the amount of elements that you need - you can do this by either creating the vector with as many elements as you need, use the resize function or change your function to create a vector, push_back the elements on it and return it.

See http://cplusplus.com/reference/stl/vector/ for details.
May 21, 2012 at 3:31pm
students has to be of type std::vector<studentType>
May 22, 2012 at 6:16pm
Peter, this is before my prototype:
1
2
3
4
5
6
7
8
9
struct studentType {
	std::string stStudentFName;
	std::string stStudentLName;
	int nTestScore;
	char chGrade;
	bool bHasHighestScoreFlag;
};

std::vector<studentType> students(20);


Is that what you mean?
May 22, 2012 at 6:16pm
hanst,

How should my function call be different?
May 22, 2012 at 6:44pm
One problem solved: I defined my variable twice. Once like this: std::vector<studentType> students(20);and once like this: studentType students;.
Topic archived. No new replies allowed.