具有两个字符串向量的搜索函数

Search Function with Two String Vectors

本文关键字:向量 字符串 搜索 函数 两个      更新时间:2023-10-16

我正在尝试创建一个可搜索的数据库,它从用户那里接收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是如何进行搜索或存储数据的。当你想出更好的方法来存储和搜索食谱周围的其他代码时,永远不需要更改。