|
Real Power of STL Revealed - Part II Now let's take more complex task: instead of character type for column labeling we will design our own class Column. New Column class will handle labels of unlimited length. However, we will not use its new features. This STL sample is intended to show how to construct data structures compatible with STL algorithm library. You can view or download source code, as well as output in text format. class Column {
}; Class Column have one data member of string type - mNo (column number), three constructors, operator "()" to access column number, two assignment operators (assign character and assign Column object), compare function, and put to operator "<<" which writes Column number to output stream. Additionally, we need compare operators "==" and "<" for class Column, and increment operator "++" (to increment column number). inline bool operator == (const Column &col1, const Column &col2) { return col1.Compare(col2) == 0; }; inline bool operator < (const Column &col1, const Column &col2) { return col1.Compare(col2) == -1; }; inline Column &operator++(Column &col) { ++col.mNo[0]; return col; }; Source code require few changes in order to use new Column class. First of all, we need to redefine spreadsheet's column and row label pair type. typedef pair<Column, int> SpSheetLabPairType; Second, calls like make_pair('a', 1) should be replaced with make_pair(Column('a'), 1). Third, columns and rows number generator needs to be rewritten. struct SpShLab_GenColsAndRowsNo /** Columns and rows number generator (a1, a2, ..., b1, b2, ...). */ {
}; Forth, within comparison classes CmpByColNo_Less and CmpByColNo_Greater statements xxx.first should be changes to xxx.first(). That's all. Now we can run our sample. The output is similar to previous one generated by the simpler version of STL demo. Take a close look to the following lines: sort(splv.begin(), splv.end(), greater<SpSheetLabPairType>()); sort(splv.begin(), splv.end(), greater_equal<SpSheetLabPairType>()); sort(splv.begin(), splv.end(), less_equal<SpSheetLabPairType>()); Functions used to compare column&row pair in above sort samples require some extra operators for class Column like ">", ">=", "<=" , right? They have been automatically generated by STL using "==" and "<". Often knowledge of underhand details may help to understand certain things. For example, abstract representation of class vector may look like this:
}; I believe it is clear why you should never access item pointed by iterator end() and why operations which cause reallocation of data buffer may invalidate all or some iterators. |