Puvendran wrote:
Does the following help ?
#include <iostream>
#include <string>
#include <list>
#include <vector>
#include <algorithm>
using namespace std;
class Message
{
public:
Message( std::string From, std::string Subject, std::string Body )
: m_From( From ), m_Subject( Subject ), m_Body( Body )
{}
void Print()
{ cout << "***************************\n"
<< "From : " << m_From << "\n"
<< "Subject : " << m_Subject << "\n"
<< "Body : " << m_Body << "\n";
}
friend bool SortByFrom( const Message* rhs, const Message* lhs );
friend bool SortBySubject( const Message* rhs, const Message* lhs );
protected:
std::string m_From;
std::string m_Subject;
std::string m_Body;
};
bool SortByFrom( const Message* lhs, const Message* rhs )
{
return lhs->m_From < rhs->m_From;
}
bool SortBySubject( const Message* lhs, const Message* rhs )
{
return lhs->m_Subject < rhs->m_Subject;
}
int main()
{
list< Message > TheMessages;
vector< Message* > Sorted[2];
//
// strore the messages somewhere
//
TheMessages.push_back( Message( "Kalle", "Your Problem", "This should do it" ) );
TheMessages.push_back( Message( "Tom", "Time?", "Hi. Do you have time?" ) );
TheMessages.push_back( Message( "Agnes", "[Re]Time?", "No. I don't?" ) );
TheMessages.push_back( Message( "Bart", "Universe", "42" ) );
//
// fetch the pointers from the original messages
// and store them in the vectors. Note: Since I have
// stored the messages in a list rather then in a vector
// the pointers will remain valid, even if the list gets
// larger
for( list<Message>::iterator il = TheMessages.begin();
il != TheMessages.end();
il++ ) {
Sorted[0].push_back( &(*il) );
Sorted[1].push_back( &(*il) );
}
// now sort the arrays holding the pointers
std::sort( Sorted[0].begin(), Sorted[0].end(), SortByFrom );
std::sort( Sorted[1].begin(), Sorted[1].end(), SortBySubject );
cout << "\nSorted by From field\n";
for( int i = 0; i < Sorted[0].size(); ++i )
Sorted[0][i]->Print();
cout << "\nSorted by Subject field\n";
for( i = 0; i < Sorted[1].size(); ++i )
Sorted[1][i]->Print();
return 0;
}
--
Karl Heinz Buchegger
kb******@gascad.at