Re: problem with sort
Gaijinco wrote:
I'm not quite sure why this code doesn't works:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
class word
{
string letters;
string sorted;
public:
word(string&s)
{
letters=s;
sort(s.begin(),s.end());
sorted=s;
}
Are you sure, you want this constructor to have the side-effect of sorting
the parameter passed? What about:
word ( string const & s )
: letters ( s )
, sorted ( s )
{
sort( sorted.begin(), sorted.end() );
}
friend bool lt(word& a, word& b)
{
return (a.sorted < b.sorted) < 0 ? true: false;
Huh? operator< returns a bool, it is not a three-way comparison yielding an
int. What about:
return ( a.sorted < b.sorted );
}
friend ostream& operator<<(ostream& out, vector<word>& v)
This should be:
friend ostream& operator<< ( ostream& out, vector<word> const & v )
unless you want the output operator to modify its argument.
{
for(int i=0; i<v.size(); ++i)
cout << v[i].letters << endl;
return out;
}
};
int main()
{
vector<word>dict;
string aux;
cin >> aux;
while(aux!="#")
{
word w(aux);
dict.push_back(w);
cin >> aux;
}
sort(dict.begin(),dict.end(),lt);
cout << dict << endl;
return 0;
}
There's something wrong with the function "lt" but i'm not sure what.
In the prototype it says:
StrictWeakOrdering cmp but I'm not sure what does that mean, maybe
something about the kind of iterators I need to use?
Soring a dictionary according to the lexicographic order of internally
rearranged words seems to be a rather strange requirement. Are you sure,
your want that?
Best
Kai-Uwe Bux