mrc...@cox.net (Mike Copeland) wrote in
news:MPG.2d288ec04...@news.eternal-september.org:
> To "template-ize" a class/struct sort override? I have the
> following
> structure:
> struct RelayTeamType
> {
> time_t totalTime; // Total Time
> int bib1, bib2; // Bib# #1 & Bib# #2
> int numFins; // # Finishers
> char ttc; // Team Type Code
> string rtCode, rtTeamName;
> string sortKey; // derived sort key
> bool operator<(const RelayTeamType &a) const
> {
> return sortKey < a.sortKey;
> }
> } extern rtWork;
> extern vector<RelayTeamType> rtVect;
> extern vector<RelayTeamType>::iterator relIter;
>
> Currently, I'm constructing the "sortKey" variable by passing
> through
> the entire vector and using different variables in the struct (e.g.
> "rtCode" or "totalTime", etc.), followed by the sort. This is simple
> enough, but it takes processing time I want to avoid.
> I'd like to be able to sort the vector on different fields, and it
> would be nice if I could do it via a "template" interface. Is this
> possible somehow? TIA
Not sure if this is what you want, but here is an example demonstrating
sorting the same vector by different sorting criteria, which are passed
as template arguments:
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
struct RelayTeamType
{
time_t totalTime; // Total Time
int bib1, bib2; // Bib# #1 & Bib# #2
int numFins; // # Finishers
char ttc; // Team Type Code
std::string rtCode, rtTeamName;
};
struct SortByTotalTime {
bool operator()(const RelayTeamType& a, const RelayTeamType& b) {
return a.totalTime<b.totalTime;
}
};
struct SortByTeamName {
bool operator()(const RelayTeamType& a, const RelayTeamType& b) {
return a.rtTeamName<b.rtTeamName;
}
};
template<class SORTER>
void ProcessMyTeams(std::vector<RelayTeamType>& teams) {
std::sort(teams.begin(), teams.end(), SORTER());
for (size_t i=0; i<teams.size(); ++i) {
std::cout << " " << teams[i].rtTeamName
<< ", total time " << teams[i].totalTime << "\n";
}
}
int main() {
RelayTeamType example_data[] =
{
{100, 2, 3, 4, 5, "red", "Alpha"},
{50, 2, 3, 4, 5, "green", "Gamma"},
{150, 2, 3, 4, 5, "red", "Beta"},
};
std::vector<RelayTeamType> teams(example_data,
example_data+sizeof(example_data)/sizeof(example_data[0]));
std::cout << "\nProcessing in order of total times:\n";
ProcessMyTeams<SortByTotalTime>(teams);
std::cout << "\nProcessing in order of names:\n";
ProcessMyTeams<SortByTeamName>(teams);
}
--- Output is: ---
Processing in order of total times:
Gamma, total time 50
Alpha, total time 100
Beta, total time 150
Processing in order of names:
Alpha, total time 100
Beta, total time 150
Gamma, total time 50