如何使我的单词查找更清晰、更高效
How can I make my word lookup cleaner and more efficient?
编写一个程序,"哔哔"出你不喜欢的单词;也就是说,你用cin阅读单词并打印出来再次在库特。如果一个词是你定义的几个词之一,你写出BLEEP而不是那个词。入手一个"不喜欢的词",例如不喜欢的字符串="西兰花";当它有效时,再添加一些。
所以我在考虑如何创建一个代码,使用向量用一组单词来做到这一点,但我能想到的只是
int main()
{
vector<string> disliked = { "damn","stupid","fat" };
string word = "";
while (cin >> word) {
bool bad = false;
for (string x : disliked) {
if (x == word)
bad = true;
}
if (bad)
cout << "Bleepn";
else
cout << word << "n";
}
return 0;
}
我觉得可以通过取出其中一个 if 语句来缩短该代码,但我找不到一种方法来做到这一点。总的来说,对于这个简单的检查,代码似乎比应该的要多,对于部分也可以做得更好吗?在向量有 1000 个单词的情况下,对整个向量进行整个循环似乎过于资源密集,也许可以通过检查 a-d、f-j 的 if 语句将其分开......等等,然后只有运行一个 for 循环会不那么重?
对向量进行排序并使用std::binary_search
:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<std::string> disliked = { "damn","stupid","fat" };
sort(std::begin(disliked), std::end(disliked));
std::string word = "";
while (std::cin >> word)
{
if ( binary_search(std::begin(disliked), std::end(disliked), word))
{
std::cout << "Bleep ";
}
else
{
std::cout << word;
}
}
}
或使用std::set
而不是矢量:
#include <iostream>
#include <set>
#include <algorithm>
int main()
{
std::set<std::string> disliked = { "damn","stupid","fat" };
std::string word = "";
while (std::cin >> word)
{
if ( disliked.find(word) != std::end(disliked) )
{
std::cout << "Bleep ";
}
else
{
std::cout << word;
}
}
}
这两种解决方案对于单词查找而不是线性都具有对数复杂性。
对向量使用 std::find
运算。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<string> disliked = { "damn","stupid","fat" };
string word = "";
while (cin >> word) {
if ( std::find(disliked.begin(), disliked.end(), word) != disliked.end() )
{
cout << "Bleep ";
}
else
{
cout << word;
}
}
return 0;
}
相关文章:
- C++中高效的大型稀疏块压缩线性方程
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 如何在C++中高效地构造随机骰子
- 如何实现高效的算法来计算大型数据集的多个不同值?
- 更高效地在微控制器上对C++进行基准测试
- 从C++无序集合中高效提取元素
- 高效的字符串截断算法,按顺序删除相等的前缀和后缀
- C++中特征对角矩阵类型的高效存储
- 高效简单的结构比较运算符
- 使用 Rcpp 的高效矩阵子集
- C++ 包含特征矩阵的类的高效算术运算符重载
- CUDA 高效的 nd-array(张量)切片
- 大多数基本类型的高效二进制序列化
- RAM高效C++属性
- 如何为球形物体和三角形地形提供高效的碰撞检测和响应
- 如何实现四个 i8 元素组的高效_mm256_madd_epi8点积
- 如何在嵌套映射(C++)中高效地查找密钥
- 在C++中高效地保存许多连续记录的图像
- 如何使我的单词查找更清晰、更高效
- 清晰高效的三维测距树实现