Help figuring out code

I am studying some code and i can't figure out what is going on here.
Record is a class by the way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
vector<Record> students;

	for (int i = 0; i < 5; i++)
	{
		Record* rec = new Record();
		cin >> rec->name;
		cin >> rec->j_num;
		cin >> rec->gpa;

		students.push_back((*rec));

	};

	vector<Record>::iterator iter;
	
	for (iter = students.begin(); iter != students.end(); iter++){
		Record rec = *iter;
		

		cout << rec.name << "\t" << rec.gpa << endl;
	};
This code is quite straight forward. I'd suggest you review the std::vector tutorial.
http://www.cplusplus.com/reference/vector/vector/

Line 3: Loop 5 times
Line 5: Allocate a new Record instance and assign it to the rec pointer.
Lines 6-8: Input some data to the Record instance.
Line 10: Push the new rec instance onto the students vector by value.

Lines 16-21: Iterate through the vector printing information from each Record iinstace.

BTW: There is a memory leak in this code. Line 5 allocates a new Record instance each time through the loop. This memory is never released. There is no reason Record needs to be dynamically allocated since it is pushed onto the vector by value.

Also, at lne 17, the Record instance is copied. This is unnecessary and inefficient since the Record instance can be accessed by using iter as a pointer.
Topic archived. No new replies allowed.