
std::list<string>::sort (Cmp)
I dont know much about this but the following works for me. I didn't think
that the sort algorithm would use
the overloaded ().
Try this
#include <vector>
#include <algorithm>
#include <functional>
#include <stdlib.h>
class ID
{
public:
ID(char letter='z',int number=0){m_letter=letter;m_number=number;}
bool operator<( const ID& id);
bool operator==(const ID& id);
virtual ~ID(){}
char m_letter;
int m_number;
Quote:
};
bool ID::operator <(const ID& id)
{
return (m_number<id.m_number);
Quote:
}
bool ID::operator ==(const ID& id)
{
return (m_number==id.m_number);
Quote:
}
int main()
{
std::vector<ID> myVect;
for (int n=0;n<20;n++)
myVect.push_back(ID((char)(100+((float)rand()/0x7fff)*100),
rand()
));
for (n=0;n<20;n++)
printf("%c ,%i \n",myVect[n].m_letter,myVect[n].m_number);
std::sort( myVect.begin( ), myVect.end( ),std::less<ID>);
for (n=0;n<20;n++)
printf("%c ,%i \n",myVect[n].m_letter,myVect[n].m_number);
return 1;
Quote:
}
}
>I'm trying to understand the mechanism to sort a list in several different
>ways. For instance, if I have a list of stings, I may want to sort the
list
>alphabetically, by length, by some known substring or by who knows what.
>I've been reading Stroustrop (C++ Programming Language 3rd Edition) and
>Deitel & Deitel (C++ How to Program) and both of these books indicate that
>this should be an easy thing to do. Well, I haven't been able to get the
>natural seeming syntax to even compile. The below code compiles but
doesn't
>produce the desired results because my overloaded operator() doesn't get
>called. The actual results indicate that the string > operator is the one
>that's called.
>So what am I doing wrong? Where can I find an example of this technique?
>Any help would be greatly appreciated!
>// File: SortTest.cpp
>#pragma warning(disable:4786)
>#include <iostream>
>#include <string>
>#include <list>
>using namespace std;
>struct longer : public greater <string>
> {
> longer () {};
> bool operator() (const string& x, const string& y) const
> { return x.length () > y.length (); };
> };
>void PrintOut (string str, list <string> theList)
> {
> list <string>::iterator i;
> cout << endl << str << endl << endl;
> for (i=theList.begin (); i!=theList.end (); ++i)
> cout << *i << endl;
> }
>int main (int argc, char* argv[])
> {
> list <string> listStuff;
> listStuff.push_back ("qwerty");
> listStuff.push_back ("asdf");
> listStuff.push_back ("this is a test");
> listStuff.push_back ("do not pass GO!");
> listStuff.push_back ("do not collect $200");
> listStuff.push_back ("this is");
> listStuff.push_back ("only a test");
> PrintOut ("Original list", listStuff);
> longer x;
> listStuff.sort (x);
> PrintOut ("List sorted on length", listStuff);
> return 0;
> }