Hey everyone, this is my first post on this site. I have been playing around with C++ a little and I require a bit of help.
I have made this simple program that creates a Student class and asks the user to input a Student I.D, Last Name and First Name. You can store multiple students and the file is output as a .txt file.
The question I have is this...I wish to make it so that the students are stored in order in relation to their I.D number (smallest to largest),
For example,
ID: 011111
Last name: Holland
First Name: Tom
ID: 022222
Last Name: Abode
First Name: Andrew
I have tried using vectors, but it just turned out to be a mess. Any help would be greatly appreciated.
There are two ways to do this in my opinion. One is manipulating the data in ram and then storing it. The other would be storing it then rearranging it. I would prefer the first one. So instead of directly writing to the file you could save your key : in this case ID in an array. Since it is a number you could use the standard qsort algorithm. If you need something more advanced you could use the STL set container and overload the < operator for your student class. Then inserting elements to the Set will mean that those elements are sorted automatically and also printing out to a file is a game :)
Thanks Silvermaul. Yeah so I get it to store the I.D numbers in an array, from there I can sort them numerically however once this is done I have no idea how to assign them back with their original first and last names?
Don't store the I.D's in the arrays. Store the objects themselves or pointers of the objects and sort them by using the I.D as comparison. This way your objects as a whole will be sorted :)
Oh yup, thats what I originally thought of doing before I came onto the forum. I just didn't know how to do it! I will give it another try though, It sounds straight forward!
Thanks man.
Hi Tomau, I was wondering if you figured out how to do the sorting, because I was facing a similar problem. I had set up a multidimensional array, instead of a class, to store names and numbers in different columns, and wanted to sort the rows of names based on the numbers, highest to lowest. I made my own topic, and someone suggested using classes instead, so I just wanted to know if you were able to figure out the sorting with the classes before I went to rewrite my own code. If possible, can you tell me what sorting code or algorithm you used?
Hey thanks for the reply's guys! I still couldn't get it to work though, so I think I'll ask a professor once I get back to university in a couple of weeks.