fork(1) download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <algorithm>
  5. using namespace std;
  7. bool less_than(string x, string y) {
  8. sort(x.begin(), x.end());
  9. sort(y.begin(), y.end());
  10. return x < y;
  11. }
  13. bool is_anagram(string x, string y) {
  14. if (x != y) {
  15. sort(x.begin(), x.end());
  16. sort(y.begin(), y.end());
  17. return x == y;
  18. }
  19. return false;
  20. }
  22. int main() {
  23. vector<string> voc; // словарь (можно использовать массив с запасом)
  24. string word; // очередное слово
  25. while (cin >> word) voc.push_back(word); // читаем и запоминаем слово
  26. sort(voc.begin(), voc.end(), less_than); // по использованию букв
  27. bool found = false;
  28. cout << "Anagrams list:";
  29. for (auto i = voc.begin(); i != voc.end() - 1; i++) {
  30. if (is_anagram(*i, *(i + 1))) {
  31. if (!found) cout << endl << *i << " ";
  32. cout << *(i + 1) << " ";
  33. found = true;
  34. } else found = false;
  35. }
  36. }
Success #stdin #stdout 0.02s 3444KB
the and a to I is of have you he  it in not was that  his doon with she at say her for as are we but can him they up  what out me go get this from be look  my there know all one no see will back into like if were then an come think so down your them would about man take just by am now over make been or time when hand who want here tell off right their turn two through eye head other how some more around door room face day where way night well thing open away give only something ask move stand good find again little try too still hear walk before leave sit let long call feel close very why which car any hold work run never start even light than after put yes stop old watch first may talk another cut mean pull behind smile our toward towards much its house keep place begin nothing year woman side because three seem wait need moment himself stare arm use voice last late across sure front sound big really name should new anything against guy kill point small happen wall black step window life maybe fall own far under boy end those reach while floor street help girl next few white must feet table these show okay enough phone body same minute shake water fire inside break ever follow second nod meet great yeah each mind suddenly dead almost gun both speak love pick home without win once word better every god build until beat course lot drive bring along five hard air continue most pass always kid believe half line high set read world hour office play young answer shoot dark laugh bed thank remember drop friend though glass hair hell catch mother four listen understand sir lose lie between live money father morning red please everything slowly rise die else kind wear hit hang many someone drink stay shoulder past grab question part case mouth throw enter hundred cover blood check outside large change push sorry bad top chair finger lead scream ground already forward figure touch become yet also desk clear real carry sleep glance seat matter number ship full police twenty send gonna together ten roll return such near miss pay paper rest appear park above onto control fly pause road probably finally guard draw city deep job ring fight leg wonder lean since hope left sign cross suppose order eat corner wrong tear shit six soon fast bill quickly shadow wife dress damn guess myself care raise mile land perhaps bar blue idea death alone best dad whole tree force fill crowd shut business blow cry write notice fine quite power fact pretty week nice lock story dog least empty everyone wave several silence short cold problem fucking cop thousand approach realize rock piece wind box either sort kiss edge interest surprise bit forget stick heart finish fuck grow ago bag sense picture ready chance worry ahead couple press doctor book officer anyone son pocket human family safe burn breath early jump lift green reason lay free machine beside stuff wide round expect neck careful lip school hide deal whisper space herself baby climb easy plan yourself trouble slide thirty train low key different swing coffee radio hotel anyway shout state study foot slow station brother hurt game heavy lady below kitchen buy area knock star decide view flash sun month straight truck shirt remain whatever sky suit hot boat ride fear pain note sight wish slip hall actually group learn race dollar true children shot afraid except grin cause exactly mark stone computer huge less explain spot upon reply clean centre corridor chest ear report dream living middle wheel bottle somebody able movie driver happy murder rather offer quiet rush rain today freeze bank bedroom kick field beautiful stair form angle darkness card person nobody hole earth gray snap war within music skin sea cigarette lower attention direction ice knee search company eight block save smell track weapon horse apartment reveal charge record clothes child beyond spend tonight loud tire shrug slam position arrive animal brown  somewhere tape soldier nose tight paint agent hate knife colour strike party fifty quick security news tomorrow strange speed disappear hurry distance file deck possible beneath bright country handle act afternoon metal telephone evening seven certain crash quietly shall frame island store food bathroom mom mirror plane shape sigh throat fade important main sometimes ball tie crack dance engine exit itself letter bear board join shock everybody add spin ass blade yard hello alive mine pack silent teeth crazy gate none third wake age truth strong clock camera image noise marry wood law trust consider million remove yell struggle promise instead among amongst tiny slightly shop hospital Jesus bend count cool agree river scare during information system surface service bridge attack lawyer sing motion ray hill elevator twist dry thick chief button level general flight brain page pour doorway tall jacket bone sink gotta circle gaze soft drag desert certainly fish beach single team bottom secret allow immediately concern husband burst forty sell leap pound escape cloud rear gold simply message detective manage creature themselves roof inch dinner gesture army switch nurse expression yellow sergeant warm roar club pop grand bite coat size however cat type thin dozen crew present shoe beer doubt settle daughter anybody grip completely nearly pair nine gather bud bird sister special hallway base mountain flat sweat gently spread wire bullet stretch master cell counter private king flame sick rip entrance sheet entire steal warn judge perfect command sharp scene screen conversation dear whether toss cup ceiling fit narrow imagine Christ simple colonel pilot cheek grace photo buddy excuse frown tunnel fix hat snow planet glow double recognize sudden steel worse wipe stupid monitor test square mention uniform south travel mask fifteen class path match grant memory serious softly dust major wild calm dig angry wet contact tank wrap action click tower crawl whose prepare thought load situation trip ignore lieutenant enjoy wing belt gas sweep north stage bet bother peer poor neither barely rifle west row beam storm wound plate share shift drug date plastic ghost pale loose aside emerge hesitate often mistake bang heat bow list movement complete include feed blast explode bitch weight yours address church surround pile worth attempt nervous government dawn trail plant final passenger pool town wash pace smash television panic self admit directly serve map fat van commander goddamn somehow post frighten continuous blind jerk blink boss nor operation glad pistol suggest teach although lucky rule apart bloody flip flesh witness quarter relax clearly repeat asleep helicopter killer member parent odd bomb release unless punch history busy bond copy accept destroy anymore cab experience shove bastard fool fold twelve evidence bus brief tap drift prove personal rub interrupt brush rope alarm aware east terrible tip spring protect  involve whip lunch reporter bell suspect evil booth tone chamber shower examine sweet choice palm assume obviously traffic hook wrist cabin enemy smoke silver pipe normal chase secretary discover wine gasp fail dive breathe moon dissolve sex ace newspaper twice choose float uncle aim public section dangerous shine gentleman song effect nearby flower faint pat confuse visit film future queen stomach demand department boot trap mess battle photograph impossible mad guest joke taste forth fist squeeze especially stun wooden leather slap purpose band tough vehicle focus usually video luck iron effort duty chick waste fresh glare swear beauty tongue fun cable backward honour cash alien detail lab director hardly clerk fence crime strip familiar local price signal giant chain smart various pants opposite breathing object grass apparently lobby dial naked intend honey support blond blonde print suck garage pattern clutch faith sand tail student swim dirty forehead strength anger laughter distant subject remind garden forest camp snake echo partner military client everywhere skull exchange program usual restaurant equipment hug difficult till buck react rich swallow curtain bury stream president wanna soul duck bolt display golden pressure indicate bay startle avoid breast condition sip code account tremble data mutter anywhere library welcome prison kneel lake instant airport cast indeed claim target pin respect art easily attorney fair muscle horror bare beast pleasure puzzle grave trace excite length mount risk ocean energy amaze envelope contain audience stumble leader difference barrel wonderful demon besides dirt accident steady interior mission victim absolutely patient occur alright receive split practice upstairs panel ease advance couch correct firm smooth powerful slight scan credit unit glove claw gear engineer awake ought stack flow whom belong ancient decision direct cap highway exist oil monster missing temple spit ma chin priest extend sake magazine mass ticket weather damage spill refuse vision event flashlight manager presence drawer thumb favour march create jam danger respond summer assistant massive century shatter female strain justice project emergency customer pad collapse arrest trick series electric electrical bug lap rail sixty porch screw cliff pump design response fellow supply mill alley style tube bowl orange perfectly shotgun necessary pink obvious village policeman closet result regard possibly hiss sidewalk stride breakfast trunk stranger dude employ branch enormous site lamp butt cage college terrify ruin totally wander bore manner yesterday produce hood cost nail discuss shell whistle dock feature dining buzz heaven upset steam bunch basement junior scar bleed nature curve official taxi court greet silently rough explosion piss replace drunk process curse jungle seal dump particular sport reaction cook stir intelligence embarrass seek pen survive central staff crouch rabbit creep castle observe arrange scratch bat range murmur towel cough hire swell medical male heel separate cheer aircraft convince forever pitch upper treat instantly knowledge rat cave degree dodge connect prisoner scramble visible pretend plain vanish shelf player universe script flicker weird balance language blank issue weak surely entirely shield marine overhead solid sail stagger elbow pit needle mister eleven platform mostly rapidly egg dare owner suffer hammer thunder corpse stroke heavily clip total helmet bench source scatter eventually spray trade mix descend sonny boom crush relief senator trigger insist deliver conference terror jar argue require worst recall halt badly collect rage blanket tray drip limit fan attach upward dim deputy sad flick carpet expose sob strap natural curious starling stern comment bounce threaten lovely waiter moan exhaust nervously likely sailor concentrate character defense term random rose slope abruptly fashion awful glimpse describe extra purse fully squad peace mail briefly spirit nowhere holy thrust operate otherwise current groan stain horn rocky admiral diamond cock waist merely chuckle despite concrete chip common magic folk dart professional fault avenue devil tuck brand tense chew bye emotion ash suitcase bound wolf trailer cockpit tea unable national determine hungry quit register announce worker sunlight jail bride plenty grunt proud adjust gift satisfy grasp angel Christmas owe guide disturb reflect united willing title blame interview gut howl mouse beg vast cheap bike model impress gang automatic haul patrol lawn criminal comfort legal ladder physical rate rumble troop device bark comfortable mayor hunt joint provide tumble deeply snatch background appreciate possibility whale hunter unlock monkey fourth receiver nerve hip pot launch joy authority Sunday shade gain motel string widen jaw briefcase choke meter hum meat brick identify recover bush drain abandon clothing fry protest bump original professor museum connection content lane licence particularly county cigar candy port eyebrow rattle shiver shriek beard assure stock coast hatch disgust valley lick rack broad lack patch opinion growl suite pray ugly secure increase jury straighten jeep activity dusk skip locate driveway motor wallet gentle package sleeve collar rag opportunity curl drill tightly seventy hero poke breeze market friendly teacher slice wildly shaft rescue cabinet downstairs innocent belly ankle marshal marshall scientist reverse Saturday material knot shudder reality mood rent whoever investigation tent theatre farm knight honest dumb research limp fling winter percent appearance depend bean sharply cord nightmare tilt amount dot fuel neighborhood neighbourhood speech stall progress torch tool sandwich cart statement shave handsome nut channel furious lightning route relieve pillow aunt halfway invite somewhat bullshit request proper plunge contract desperate footstep truly rubber wagon rocket fighter tug item embrace lover brilliant waitress splash structure desperately poison flood asshole peel according blaze goodbye height swirl retreat insert streak pure technician shore prefer wade underneath darling amber introduce closely milk theory lid walker sword circumstance measure penny pierce dragon fog console definitely cling inner forgive remark stab harbour calmly dash commit hawk develop wedding gleam spell instrument horizon mud threat aboard instruction spare silly pig toilet operator seriously communication vampire gene candle toy estate marriage complex passage crane drum overlook favourite chill desire score executive mental loudly loss link sway deny steer purple jeans armour squint firmly expensive skirt hop liquid stiff cowboy sale arrow nasty aisle windshield darken siren transfer sniff sofa career navy palace treasure warrior cream amuse dangle escort coin dean meal furniture flush bubble famous twin insurance soak Wednesday exterior shepherd afford charm ourselves alert pride screenplay filter freedom hover brake establish outer flee university angrily pill rank silk regular screech document harm statue spark thigh eighty due carve blur conceal idiot mystery slave midnight guilty hut ninety sue represent remote plus bruise clay relationship neighbour tension standard individual extremely accent toe affair illuminate bust swarm hurl casually medium melt access impression uncomfortable perform unconscious locker speaker visitor laser personally anxious deserve unusual delight root proceed servant dish federal frantically robe whirl horrible fumble headlight probe invisible etc tile pleasant mist snarl staircase balcony divorce tourist joker pole column confidence lad tighten period rob fake district curb pulse expert routine terminal neat hers flag border society tour rid winder inform violet batter silhouette science agency grind doll associate minister former incredible lunge slump cautiously scrape ill headquarters pal arch dull gale maintain annoy tune hick schedule witch depth skill hush lounge coffin downward downwards sneak crap reflection robot cargo alongside log ambulance exercise bartender hollow advice argument resume casino rib native attendant habit confirm mumble senior sprawl excitement bureau refer spider lightly flap trash attitude violently explanation shelter engage throughout chunk wreck courtyard assault weep wink Friday hint freak advantage wise prop fleet whenever huddle crate deadly impact studio unknown pearl hull recently weekend scale sequence outta bandage shame urge baseball chopper spy Monday intense accompany torture birthday champagne suspicious assassin sentence fifth lonely zip proof microphone attractive political aid stamp piano admire fairly cute property wail naturally pencil regret  shed holly citizen clever downtown handkerchief ramp fortune lung article eighteen apply bless tend tan complain example basket super vault girlfriend ability limb occasionally tag earn seize therefore dealer companion confusion warehouse bath collection craft actor chaos rod occupy sack suicide funeral lesson ginger gin prevent occasion meanwhile chili fur garbage tangle peek rape ram social ordinary modern lion agreement homicide thump division laboratory horrify spike sixteen previous rumour resist notebook benefit slug debris solve journey retire chop trooper possess permit sugar conscious rig football mob hunch lone excellent pose atmosphere available apologize snort international sexual highly drape pavement lighter cuff boyfriend bind plead sting loom responsible assignment express defeat underground custom 
Anagrams list:
board broad 
break brake 
bear bare 
race care 
crate react trace 
charm march 
cat act 
add dad 
leader dealer 
danger garden 
deal lead 
read dear dare 
asleep please 
angle angel 
glare large 
anger range 
gear rage 
earth heart 
heat hate 
marine remain 
snake sneak 
weak wake 
male meal 
lane lean 
panel plane 
pale leap 
seal sale 
least steal 
mean name 
master stream 
team meat 
near earn 
are ear 
tear rate 
east seat 
taste state 
sweat waste 
tea eat 
lamp palm 
lap pal 
am ma 
ram arm 
trap part 
tap pat 
art rat 
below elbow 
bore robe 
blow bowl 
direct credit 
expect except 
rescue secure 
course source 
chin inch 
god dog 
feel flee 
whoever however 
three there 
sheet these 
keep peek 
never nerve 
flesh shelf 
life file 
horse shore 
listen silent 
live evil 
time item 
quiet quite 
resist sister 
tone note 
route outer 
super purse 
sue use 
wolf flow 
form from 
night thing 
ought tough 
grin ring 
sign sing 
gut tug 
thin hint 
this shit 
worth throw 
shout south 
how who 
sink skin 
pit tip 
its sit 
own now 
stop post spot 
pot top