Saturday, November 21, 2009

STL comparison FUNCTOR

http://www.topcoder.com/tc?module=Static&d1=match_editorials&d2=srm374


#include < iostream >
#include < vector >
#include < string >
#include < algorithm >
using namespace std;

bool isvowl(char c) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
return true;
return false;

}

struct word {
string w;
vector s1; //sorted
vector s2; //unsorted
};

// comparison function
bool operator < (const word &a, const word &b) {
if (a.s1 != b.s1) return a.s1 < b.s1;
return a.s2 < b.s2;
}


class SyllableSorting {
public:

vector sortWords(vector words) {

vector vw;


for(int i = 0; i < words.size(); ++i) {

vector syl;
word W;

string s("");
s += words[i][0];

for (int j = 1; j < words[i].length(); ++j) {
char c = words[i][j];
bool pv = isvowl(words[i][j-1]);
bool v = isvowl(c);
if (pv) { //previous char is a vowl
if (v)
s += c;
else {
syl.push_back(s);
s = c;
}
} else { // previous char is a consonant
s += c;
}
}
syl.push_back(s);

for(int k = 0; k < syl.size(); ++k)
cout << syl[k] << " ";
cout << endl;

W.w = words[i];

W.s2 = (syl);

sort(syl.begin(), syl.end());

W.s1 = (syl);

vw.push_back(W);

}

sort(vw.begin(), vw.end());
vector ret;
for(int i = 0; i < vw.size(); ++i)
ret.push_back(vw[i].w);
return ret;
}
};