Write a function to sort the array of strings so that all the conjugation words are adjacent

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.