2016-04-14 104 views
1

这是我的代码:显示1个结果与For循环

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犯规匹配任何这些,那么就打印out“它不匹配”一次。我知道如果我使用其他或如果(userinput!= temp [i] .eventID)它会显示“它不匹配”多次。我是C++新手,请帮忙。谢谢

回答

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

非常感谢你:D。祝你有个美好的一天 – Ike

+0

你也可以''返回''而不是使用标志。 –

+0

@Bob__ ...如果确保'temp'中没有两个元素具有相同的'eventID'。 – MikeCAT

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 

的是,使用该标志在其他的答案建议!我认为它会对你有好处,知道这存在

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