C++有没有一种方法可以循环遍历 vector 并仅在完全搜索完消息后才返回消息

标签 c++ vector

这只是我书中的一个练习,它要求我在一个 vector 中搜索特定名称,并在找到该名称后返回另一个对应 vector 的分数。如果找不到名称,它将返回消息“找不到名称!”

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';
    }
}

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

#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';
}

关于C++有没有一种方法可以循环遍历 vector 并仅在完全搜索完消息后才返回消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35694379/

相关文章:

c++ - 获取 vector 中 char 的位置 (C++)

c++ - C++ 中复杂的 for 和 if 条件等价于 Scala

c++ - 关于linux shell函数与C函数的关系()

c++ - 在任意加长的集合中查找最大数量是行不通的

c++ - 在从未实例化的模板中错误使用非相关名称是否需要诊断?

c++ - 除非使用完整的相对路径,否则 Eclipse CDT 无法找到包含文件

vector - 获取向量中满足条件的所有索引

c++ - 自定义 C++ 迭代器问题

c++ - 是否可能/建议将 vector 存储在结构中? C++

ios - 如何从A中减去UIBezierPath A&B的交集?