如何修正C++ vector单词排序函数?实现字母序+同字母短单词优先
单词排序逻辑修复:按字母序+同字母短优先
需求与问题
需要实现函数对vector<string>中的单词排序,规则为:
- 优先按字母顺序排序
- 若单词由相同字母组成(如
a、aaa、aaaa),则长度更短的排在前面
当前代码处理这类同字母单词时顺序混乱,无法保证短单词在前、长单词在后。原代码如下:
void sortWords() { for (int i = 0; i < wordList.size(); i++) { for (int j = 0; j < wordList.size(); j++) { string temp; for (int y = 0; y < wordList[i].size(); y++) { if (wordList[i][y] < wordList[j][y] && i != j) { temp = wordList[i]; wordList[i] = wordList[j]; wordList[j] = temp; break; } else if (wordList[i][y] > wordList[j][y] && i != j) { break; } } } } }
原代码问题分析
- 前缀场景未处理:当一个单词是另一个的前缀(如
a和aaa),内层循环仅遍历到短单词的长度就终止,未比较长度差异,导致顺序随机。 - 冒泡排序逻辑低效且错误:i和j遍历范围覆盖整个数组,存在大量无效比较;交换逻辑未针对相邻元素处理,排序稳定性差。
修复方案
方案1:使用STL sort + 自定义比较器(推荐)
利用C++标准库的sort函数,配合自定义lambda表达式实现排序规则,代码更简洁高效:
#include <algorithm> #include <vector> #include <string> void sortWords(std::vector<std::string>& wordList) { std::sort(wordList.begin(), wordList.end(), [](const std::string& a, const std::string& b) { // 先逐字符比较字母顺序 int min_len = std::min(a.size(), b.size()); for (int i = 0; i < min_len; ++i) { if (a[i] != b[i]) { return a[i] < b[i]; } } // 字符全匹配时,短单词排前面 return a.size() < b.size(); }); }
方案2:修复原有冒泡排序逻辑
如果需要保留冒泡排序的框架,调整遍历和比较逻辑:
#include <vector> #include <string> #include <algorithm> // 用于std::min void sortWords(std::vector<std::string>& wordList) { int n = wordList.size(); for (int i = 0; i < n - 1; ++i) { bool swapped = false; // 每次遍历到未排序部分的末尾 for (int j = 0; j < n - i - 1; ++j) { const std::string& curr = wordList[j]; const std::string& next = wordList[j + 1]; int min_len = std::min(curr.size(), next.size()); bool need_swap = false; // 逐字符比较 for (int y = 0; y < min_len; ++y) { if (curr[y] > next[y]) { need_swap = true; break; } else if (curr[y] < next[y]) { break; } } // 字符全相同,长单词往后放 if (!need_swap && curr.size() > next.size()) { need_swap = true; } if (need_swap) { std::swap(wordList[j], wordList[j + 1]); swapped = true; } } // 无交换说明已排序完成,提前退出 if (!swapped) break; } }
逻辑说明
两种方案的核心逻辑一致:
- 优先逐字符对比,按字母顺序决定先后;
- 当两个单词的所有对应字符都相同时,比较长度,短单词排在前面。
内容的提问来源于stack exchange,提问作者swag money wizz jizz
相关产品推荐
相关产品推荐

