这只是我书中的一个练习,它要求我在一个 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/