具有两个字符串向量的搜索函数
Search Function with Two String Vectors
我正在尝试创建一个可搜索的数据库,它从用户那里接收5种成分作为字符串向量,然后将其与文本文件中的食谱进行比较。文本文件被转换为字符串,然后被分解为字符串向量中的标记。当我尝试通过令牌搜索配料时,它会输出每一个食谱,即使搜索到的项目不在食谱中。
我检查了一下,标记化功能完美运行
我还想确保这个循环会检查每个食谱中的一种成分(而不仅仅是一次看到就停下来),有什么技巧吗?
我对C++很陌生,所以我很感激任何帮助。
void recipesearch(const vector<string>& ingredientlist) //ifstream& recipes)
{
ifstream myrecipes;
string ingredient;
string file;
vector <string> tokens;
myrecipes.open("recipes.txt");
if (myrecipes.is_open())
{
// read entire file into string
myrecipes.seekg(0, std::ios::end);
file.reserve(myrecipes.tellg());
myrecipes.seekg(0, std::ios::beg);
file.assign((std::istreambuf_iterator<char>(myrecipes)),
std::istreambuf_iterator<char>());
transform(file.begin(), file.end(), file.begin(), ::tolower);//makes database lowercase
Tokenize(file, tokens, "#");//places recipes as seperate strings into vector
for (const string & ingredient : ingredientlist) // each ingredient in ingredient vector
{
for (const string & recipe : tokens){ //each recipe in recipe vector
if (recipe.find(ingredient) != recipe.npos) // found ingredient in file
{
cout << "yo";
}
}
}
}
else cout << "Unable to open recipe file!";
myrecipes.close();
}
考虑到问题陈述,设计是不够的。但是,您提到了自己是C++的新手。如果这只是为了学术目的,我会搁置这类问题,并着手解决
您需要做的是学习如何将类序列化为文件和文件。如果你有食谱及其成分的实际类表示,以及读取和写入文件的方法,这个问题的设计会简单得多。
然后,只需要通过搜索函数的谓词搜索配方对象的集合。
我从这里开始:http://www.parashift.com/c++-faq/serialization.html
翻转两个for循环,这样您就可以在食谱中搜索配料了。当你找到一种配料时,将其标记为找到,然后寻找下一种配料。只有当所有的原料都找到了,你才会对那个食谱"哟"。
这里有一个简单而愚蠢的方法:
for (const string & recipe : tokens){ //each recipe in recipe vector
for (const string & ingredient : ingredientlist) // each ingredient in ingredient vector
{
int ingredientsfound = 0; // keep a count of the number of ingredients found.
if (recipe.find(ingredient) != recipe.npos) // found ingredient in recipe
{
ingredientsfound++;
}
}
if (ingredientsfound == ingredientlist.size())
{ // found all of the ingredients
cout << "yo";
}
}
Christopher Pisz在他们的回答中暗示了一个更好的方法:创造一个更聪明的食谱。创建一个包含字符串的类,而不是一个字符串。给这个类一个搜索成分的方法。
class Recipe
{
public:
bool requiresIngredients(const vector<string> & ingredients);
}
然后你可以
for (const Recipe & recipe : recipes){ //each recipe in recipe vector
if (recipe.requiresIngredients(ingredientlist))
{
cout << "yo"
}
}
没有人关心Recipe是如何进行搜索或存储数据的。当你想出更好的方法来存储和搜索食谱周围的其他代码时,永远不需要更改。
相关文章:
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 构造<int>具有 2 个字符串文字的向量
- 如何将元素添加到向量的字符串位置
- 将向量解析<string>为字符串
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 如何使用向量字符串令牌构建表达树
- 将 argv 复制到新的全局向量字符串
- 如何读取控制台输入并将其存储到向量字符串中
- 向量字符串push_back在C 中不起作用
- C char数组和向量字符串
- 可以直接初始化向量<字符串 *> 而不使用 new 吗?
- 迭代向量字符串的字符(C++禁止指针和整数之间的比较)
- 比较两个向量字符串的相似性C++
- 我有麻烦将字符串放入向量字符串
- 如何从一个向量字符串得到一个字符串的联合集
- 函数返回向量/字符串,但不返回数组
- 向量向量字符串固定大小
- c++向量字符串排序不工作
- C++将字符串数组[]复制到向量<字符串>