使用For循环显示1个结果

Showing 1 result with For Loop

本文关键字:1个 结果 显示 循环 For 使用      更新时间:2023-10-16

这是我的代码:

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