C++ 有没有办法循环遍历一个向量,只有在完全搜索后才返回一条消息


这只是

我书中的一个练习,它要求我在向量中搜索特定名称,并在找到名称后从另一个相应的向量返回分数。如果未找到该名称,它将返回消息"找不到名称!

int main()
{
    vector<string>name;
    vector<int>score;
    string n = "0";
    int s = 0;
    while (cin >> n >> s && n != "NoName") {
        for (int i = 0; i < name.size(); ++i)
            if (n == name[i]) {
                cout << "Error! Name is already in database!" << 'n';
                break;
            }
        name.push_back(n);
        score.push_back(s);
    }
    for (int i = 0; i < name.size(); ++i)
        cout << "(" << name[i] << " " << score[i] << ")" << 'n';
    cout << "Type in a name to find the score" << 'n';
    string search = "0";
    cin >> search;
    for (int i = (name.size() - 1); i >= 0; i = i - 1) {
        if (search == name[i])
            cout << "Score is " << score[i] << 'n';
        else
            cout << "Name not found!" << 'n';
    }
}

以上是我的代码。我遇到的唯一问题是它会遍历向量并多次返回"找不到名称!",因为它搜索每个单独的位置。我只希望它在搜索整个向量后返回消息。我尝试在谷歌上搜索它,我发现了这样的东西:

#include <algorithm>
...
std::vector<std::string>::const_iterator it = std::find(vec.begin(), vec.end(), "some string");
if (it != vec.end())
{
   std::cout << "Found '" << *it << "' in the vector." << std::endl;
}

不幸的是,我不太明白。

std::vector<std::string>::const_iterator it = std::find(vec.begin(), vec.end(), "some string");

这将搜索范围[vec.begin(), vec.end()[中的字符串"some string",并在找到该元素时返回该区域中元素的迭代器。如果未找到,则返回范围的末尾(vec.end())。

所以if (it != vec.end())if (the string was found).


关于您的原始代码和不需要的打印,有几种方法可以解决这个问题。一种方法是:

int i;
for (i = (name.size() - 1); i >= 0; i = i - 1) {
    if (search == name[i]) break; // exit the loop as soon as the element is found
}
if (i >= 0) {
    cout << "Score is " << score[i] << 'n';
} else {
    cout << "Name not found!" << 'n';
}

std::vector<std::string>::const_iterator it = std::find(name.begin(), name.end(), name_to_search);

请参考函数模板标准::查找。它搜索范围 [name.begin(), name.end()) 并将每个元素与 "name_to_search" 进行比较。它将迭代器返回到等于"name_to_search"的第一个元素。

如果没有匹配的元素,该函数将返回 name.end()

附言您也可以像这样浏览范围:

int i = 0; for (; i < name.size(); i++) { if (search == name[i]){ cout << "Score is " << score[i] << 'n'; break; } } if(i == name.size()){ cout << "Name not found!" << 'n'; }

最新更新