如何优化单词查找效率?如何实现指定单词BLEEP过滤程序?
你的两个C++问题解答:高效单词查找+禁用词屏蔽程序实现
一、如何让单词查找操作更简洁高效?
核心思路是从数据结构选型和逻辑优化入手,给你几个实用方向:
- 选对容器提升效率:如果现在用
vector存单词集合,查找时需要遍历整个容器(时间复杂度O(n)),数据量大时很慢。换成unordered_set<string>是最优解,它的平均查找时间是O(1),直接用count()或find()方法就能快速判断单词是否存在;如果必须用有序结构,把vector排序后用std::binary_search(需要包含<algorithm>头文件),时间复杂度降到O(log n),也比遍历高效。 - 统一文本格式避免冗余判断:如果需要忽略大小写(比如"Broccoli"和"broccoli"算同一个禁用词),提前把所有目标单词转成小写(或大写)存储,查找时也把输入单词转成相同格式,既不会漏判,逻辑也更简洁。
- 用标准库替代手写循环:别自己写for循环遍历查找了,直接用
std::find(针对vector)或者容器自带的成员方法(比如unordered_set::find),代码更简洁,而且标准库实现经过优化,效率更靠谱。
二、完成禁用词屏蔽程序
我一步步帮你完善,从单个禁用词开始,再扩展到多禁用词集合,最后给你优化版本:
1. 单个禁用词基础版本
先实现你提到的单个禁用词逻辑,代码很直观:
#include <iostream> #include <string> using namespace std; // 新手用这个简化代码,项目开发建议避免全局using int main() { string disliked = "Broccoli"; string word; cout << "请输入单词(输入EOF结束:Windows按Ctrl+Z,Linux按Ctrl+D):\n"; // 循环读取单词,直到输入结束 while (cin >> word) { if (word == disliked) { cout << "BLEEP "; } else { cout << word << " "; } } return 0; }
2. 扩展到vector存储多禁用词
按照你的计划用vector实现,借助std::find算法完成查找:
#include <iostream> #include <string> #include <vector> #include <algorithm> // 引入std::find需要的头文件 using namespace std; int main() { // 预定义多个禁用词 vector<string> disliked = {"Broccoli", "Cilantro", "Liver"}; string word; cout << "请输入单词(输入EOF结束):\n"; while (cin >> word) { // 在vector中查找当前单词 auto it = find(disliked.begin(), disliked.end(), word); if (it != disliked.end()) { // 找到禁用词 cout << "BLEEP "; } else { cout << word << " "; } } return 0; }
3. 优化版:用unordered_set提升查找效率
如果禁用词数量较多,vector的遍历查找效率会下降,换成unordered_set能大幅提升速度:
#include <iostream> #include <string> #include <unordered_set> using namespace std; // 可选:添加转小写函数,实现大小写不敏感的屏蔽 string to_lower(string s) { for (char& c : s) { c = tolower(static_cast<unsigned char>(c)); } return s; } int main() { unordered_set<string> disliked = {"broccoli", "cilantro", "liver", "brussels sprouts"}; string word; cout << "请输入单词(输入EOF结束):\n"; while (cin >> word) { // 转小写后查找,兼容大小写输入 string lower_word = to_lower(word); if (disliked.count(lower_word)) { cout << "BLEEP "; } else { cout << word << " "; } } return 0; }
内容的提问来源于stack exchange,提问作者Kirill
相关产品推荐
相关产品推荐

