显示1个For循环结果

时间:2016-04-14 13:23:33

标签: c++

这是我的代码:

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与其中任何一个都不匹配,那么只需打印出来&#34;它就不匹配&#34;一旦。我知道如果我使用else或if(userinput!= temp [i] .eventID)它只会显示&#34;它不匹配&#34;多次。我是C ++的新手,请帮忙。谢谢

3 个答案:

答案 0 :(得分:3)

您可以使用标记来记住是否找到了某些元素。

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

答案 1 :(得分:1)

一个很好的模式,“做旧的方式”:

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

仍然使用其他答案中建议的标志!我认为,知道存在这对你有好处

答案 2 :(得分:0)

另一种方法,几乎​​相当于在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;
}