对字符串数组进行排序,将变位词排在相邻位置
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中,也论述了变位词除了排序,也可以用统计各字符出现次数来判断
#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中,也论述了变位词除了排序,也可以用统计各字符出现次数来判断
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 在命令行用 sort 进行排序
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 文件遍历排序函数
- C#选择排序法实例分析
- C#插入法排序算法实例分析
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- C#实现Datatable排序的方法
- Lua教程(二):C++和Lua相互传递数据示例
- SQLSERVER的排序问题结果不是想要的
- Windows Powershell排序和分组管道结果
- C#通过IComparable实现ListT.sort()排序
- C#中遍历Hashtable的4种方法
- C#选择法排序实例分析
- SQL学习笔记四 聚合函数、排序方法
- C++联合体转换成C#结构的实现方法
- C#对list列表进行随机排序的方法