Question:
Need help in C++ programming!!!?
rocky
2010-05-01 05:00:44 UTC
Hi, so I am doing a C++ project which I have created a vector of students with their average test scores. how do i make a function to sort them alphabetically and another function to sort them in descending order? Also how do I edit the vector, say asking the user to enter the person's name and edit the person's name or test scores??? Thank you!!!!
Three answers:
Cubbi
2010-05-01 09:00:02 UTC
First question you have to ask is why vector? If you used set or multiset, they'd be already sorted.



But if you need vector for its fast random-access ability, you can, of course sort it at any time, like this:



sort(v.begin(), v.end());



(remember to #include )



in order for this to work, your Student class has to have operator less-then defined, otherwise sort wouldn't know which Student has to go before which one.



For alphabetical sort by name, you can make your less-then something like:



class Student {

string name;

// some other data

public:

bool operator< (const Student& rhs) const {

return name < rhs.name;

}

};





Alternatively, you can give sort() the third argument - a standalone sorting function, functor, or lambda, but I think giving your Students strict weak ordering ability is better.



As for editing a Student based on name, once your vector is sorted, you can find the student with the given name using slow linear lookup with find() or fast binary search with equal_range() or lower_bound(), but again, if you had a set/multiset (depending on whether students with identical names are forbidden or allowed), searching would have been easier as well.



You could also have used a map/multimap, mapping name to a list of scores, in which case you wouldn't even need a hand-written class.
Avinash
2010-05-01 05:18:51 UTC
You can create a class Student as:

class Student

{

string name;

long avgScore;

};



vector vStudents

You can sort students the way you sort integers.

Use stricmp to compare names of two students. If it returns negative, then first student should be listed first. Otherwise second student should come first.



For editing go through each Student in the vector and using stricmp find if names match. If they match stricmp will return 0. Then change the score of that Student.
2010-05-01 06:29:07 UTC
Google STL sort or C's quicksort


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...