Topic
Write a function to sort the array of strings so that all the modifiers are adjacent.
Answer
First, make clear what is the inflection word. A verb is a word that consists of the same letter, but with a different order. For example, live and evil are a pair of conjugation words. OK, so the meaning of this topic is very clear, it does not require us to the string array of strings in the dictionary order, otherwise we directly call the STL in the sort function is OK. It requires us to sort by the criteria of the inflection words in the process of sorting. In this case, we can still call the sort function, but write a comparison function ourselves. In general, if we want to sort an array of length n, we can call sort:
Sort (A, a+n);
But if we have an array p, where each element is a struct: person, we want to sort by the age of the person in the struct, and we need to write a comparison function cmp ourselves:
BOOL cmp (person P1, person p2) { return p1.age < p2.age;}
Then call the sort function:
Sort (P, p+n, CMP);
OK, back to our topic, our comparison function needs to sort two strings first by dictionary order, and then compare, so that the conjugation word after the dictionary order is the same. When the sort function is called, it is queued together.
The code is as follows:
#include <iostream>#include<algorithm>using namespacestd;BOOLcmpstringS1,stringS2) {Sort (S1.begin (), S1.end ()); Sort (S2.begin (), S2.end ()); returnS1 <S2;}intMain () {stringS[] = { "axyz","ABC","Yzax","BAC","Zyxa","FG","GF" }; Sort (s, S+7, CMP); for(intI=0; i<7; ++i) cout<<s[i]<<Endl; return 0;}
Write a function to sort the array of strings so that all the conjugation words are adjacent