Friday, February 12, 2010

Containers: Stick to basic types initially

STL containers may impose a few requirements on your class (say for example, class Student) before they can contain them: like comparison operators, copy-constructors and a whole bunch of other things. This can be rather daunting (not to mention irritating) for the programmer, if his class is not containment-ready just yet and there is no example/documentation at hand: the error-messages are not friendly!

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).

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;

//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.
Solution:
Here’s how you may do the grade-report task:

//Add the student info
for(..)//Iterate through the student objects one by one
(

//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}
}

Summary:
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: