使用For循环显示1个结果
Showing 1 result with For Loop
这是我的代码:
void IDsearch(vector<Weatherdata>temp)
{
int userinput;
cout << "Enter the ID of the Event and i will show you all other information: " << endl;
cin >> userinput;
for(unsigned int i = 0; i < temp.size();i++)
{
if(userinput == temp[i].eventID)
{
cout << "Location: " << temp[i].location << endl;
cout << "Begin Date: " << temp[i].begindate << endl;
cout << "Begin Time: " << temp[i].begintime << endl;
cout << "Event Type: " << temp[i].type << endl;
cout << "Death: " << temp[i].death << endl;
cout << "Injury: " << temp[i].injury << endl;
cout << "Property Damage: " << temp[i].damage << endl;
cout << "Latitude: " << temp[i].beginlat << endl;
cout << "Longitude: " << temp[i].beginlon << endl;
}
}
}
我想做的是在循环所有的值之后,如果userinput与其中任何一个都不匹配,那么只需打印一次"it不匹配"。我知道如果我使用else,或者(userinput!=temp[I].eventID)它只会多次显示"它不匹配"。我是C++新手,请帮忙。感谢
您可以使用标志来记住是否找到了一些元素。
void IDsearch(const vector<Weatherdata>&temp) // use reference for better performance
{
int userinput;
bool found = false;
cout << "Enter the ID of the Event and i will show you all other information: " << endl;
cin >> userinput;
for(unsigned int i = 0; i < temp.size();i++)
{
if(userinput == temp[i].eventID)
{
cout << "Location: " << temp[i].location << endl;
cout << "Begin Date: " << temp[i].begindate << endl;
cout << "Begin Time: " << temp[i].begintime << endl;
cout << "Event Type: " << temp[i].type << endl;
cout << "Death: " << temp[i].death << endl;
cout << "Injury: " << temp[i].injury << endl;
cout << "Property Damage: " << temp[i].damage << endl;
cout << "Latitude: " << temp[i].beginlat << endl;
cout << "Longitude: " << temp[i].beginlon << endl;
found = true;
}
}
if(!found)
{
cout << "it doesnt match" << endl;
}
}
一种很好的模式,"过去的方式":
int i;
for (i=0; i<N; i++)
if (...) {
...
break; // i does not reach N
}
if (i == N) { // never entered ifs in the for loop
尽管如此,还是按照其他答案中的建议使用标志!我认为知道的存在对你有好处
还有另一种方法,几乎相当于在for循环中使用break语句。
只需循环遍历矢量,然后将结果打印到它的外部
unsigned int i = 0;
for(; i < temp.size() && userinput != temp[i].eventID; ++i);
if(i < temp.size() && userinput == temp[i].eventID)
{
cout << "Location: " << temp[i].location << endl;
cout << "Begin Date: " << temp[i].begindate << endl;
....
}
else
{
cout << "it doesnt match" << endl;
}
相关文章:
- 如何返回一个类的两个对象相加的结果
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 这两个代码片段相似,但显示的结果不同
- Boost program_options将多个配置文件解析结果存储到一个parsed_options中
- 为什么第二个代码给出了预期的结果,而第一个代码却没有?
- oStream 不打印添加两个 valarray 的结果(使用运算符重载)
- 如何使用CPack打包多个cmake构建结果?
- QtConcurrent - 在发布到 UI 线程的数千个结果中保持 GUI 响应
- 为什么 Clang 和 GCC 中两个无符号整数之和的结果类型不同
- 我们如何并行运行算法的 n 个实例并以有效的方式计算结果函数的平均值?
- 我有两棵二叉树.我想在不更改输入树的情况下深度复制两个二叉树的结果
- 如何在 for 循环中取下第一个结果,使其不会重复
- 两个结果的std :: chrono :: high_resolution_clock :: now()给出了〜270n
- 如何使用 std::regex 匹配多个结果
- 使用For循环显示1个结果
- 为什么rand()/double(rand_MAX)的第一个结果不是随机的
- MPI_Reduce选择前k个结果
- 在将两个结果行写入文件之前比较用fprintf生成的结果行
- 程序返回多个结果
- 如何改进存储多个结果的结构