您的位置:首页 > 编程语言 > C语言/C++

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

2016-01-26 17:44 483 查看
#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中,也论述了变位词除了排序,也可以用统计各字符出现次数来判断
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息