[C++]对字符串向量排序

来源:互联网 发布:js 当前页刷新 编辑:程序博客网 时间:2024/06/02 10:53

让字符串向量首先按字符串长度进行排序,长度短的在前,长的在后。如果长度相等则按字典序排序,并移除重复的字符串。

去重复并按字典序排序:

void elimDumps(vector<string> &words){// 按字典序排序sort(words.begin(), words.end());// unique重排输入范围,使得每个单词只出现一次// 并排列在范围的前部,返回指向不重复区域之后一个位置的迭代器auto end_unique = unique(words.begin(), words.end());// 删除重复单词words.erase(end_unique, words.end());}

比较函数,用来按长度排序单词:

bool isShorter(const string &s1, const string &s2){return s1.size() < s2.size();}

主函数:

int _tmain(int argc, _TCHAR* argv[]){// 创建并初始化字符串向量vector<string> words{ "aaa", "c", "eeee", "b", "cccc", "c" };// 移除重复单词并按字典序排序elimDumps(words);// 将向量按字符串大小排序,使用稳定排序算法保持相同长度的单词按字典序排列stable_sort(words.begin(), words.end(), isShorter);for (auto &s : words){cout << s << endl;}return 0;}

程序执行结果:


0 0
原创粉丝点击