对字符串数组进行排序,将变位词排在相邻位置

来源:互联网 发布:淘宝上的卫生巾能买吗 编辑:程序博客网 时间:2024/04/30 17:25

#include<iostream>#include<string>#include<vector>#include<hash_map>#include<list>#include<algorithm>using namespace std;string sortChars(string s){sort(s.begin(), s.end(), less<char>());return s;}void sort(vector<string>& array){hash_map<string, list<string>> hash;list<string> l;auto it = array.begin();for (; it != array.end(); ++it){string key = sortChars(*it);auto hashiterator = hash.find(key);if (hashiterator == hash.end()){hash[key] = l;}hash[key].push_back(*it);}int index = 0;for (auto hashkey = hash.begin(); hashkey != hash.end(); ++hashkey){for (auto listIt = (*hashkey).second.begin(); listIt != (*hashkey).second.end(); ++listIt){array[index] = *listIt;index++;}}}void show(vector<string> a){for (auto it = a.begin(); it != a.end(); it++)cout << *it << "   ";cout << endl;}int main(){vector<string> a;a.push_back("acre");a.push_back("hello"); a.push_back("syntax"); a.push_back("care");a.push_back("fatigue"); a.push_back("race");a.push_back("misinterpretation"); a.push_back("montony");show(a);cout << endl; cout << endl; cout << endl;sort(a);show(a);cin.get();return 0;}
执行结果:





如果需要改变单词则可在string sortChars(string s)中加上引用string sortChars(string& s),执行结果:


当然在编程珠玑2.4中,也论述了变位词除了排序,也可以用统计各字符出现次数来判断

0 0
原创粉丝点击