There might be quite a bit of boiler-plate code to add to the class Student before you can use STL containers to contain Student objects. Rather than getting your program’s core functionality up, you may find yourself just plugging in mundane code into your data-types, not to talk about all those strange-looking and mostly unreadable error-messages.
Example:
Say you want to make a grade-report for a group of students. It’s as simple as putting all your student records in an std::multimap, with Grade as key and iterating through the filled in multi-map (which groups the records according to the key).
Tip 1: Work with pointers to your class. The use of the pointer also makes for better efficiency: no copies of your objects!
multimap<Grade, Student*> gaGradeReport;
Again depending on the contents of the class Grade, the compiler may squeal! It needs a comparison type LessThan before it can work…which brings me to Tip 2…
Tip 2: Use basic data-types for your key in associative containers like std::set, std::map etc. The easiest way to do it is to provide a conversion operator to a basic type for your key class.
Here’s how you may do the grade-report task:
//Add the student info
Work with basic data-types (pointers are basic data-types) for STL containers for more rapid development. Plug in the boiler-plate later.
class Student
{
string m_sName;
RollNumber m_xID;
Grade m_xGrade;
}
Tip 1: Work with pointers to your class. The use of the pointer also makes for better efficiency: no copies of your objects!
multimap<Grade, Student*> gaGradeReport;
Again depending on the contents of the class Grade, the compiler may squeal! It needs a comparison type LessThan before it can work…which brings me to Tip 2…
Tip 2: Use basic data-types for your key in associative containers like std::set, std::map etc. The easiest way to do it is to provide a conversion operator to a basic type for your key class.
multimap<short, Student*> gaGradeReport;Solution:
//After providing conversion to short
class Grade{... operator short() {...}}
Implement your program on these lines, get it working and then do the boiler-plate stuff.
Here’s how you may do the grade-report task:
//Add the student info
for(..)//Iterate through the student objects one by oneSummary:
(
//Get the address of student record in pxStudent
gaGradeReport.insert(pair<short, Student*>(short(pxStudent->m_xGrade),pxStudent);
}
//Print the GradeReport multimap
for(..//each grade)
{
for(..//each record in range)
{//print the record}
}
Work with basic data-types (pointers are basic data-types) for STL containers for more rapid development. Plug in the boiler-plate later.
No comments:
Post a Comment