1

In this program, the user must type in an 3 letter departing airport code (userFlight) and I will give them back the possible destinations. To check that what they typed in is one of the valid airport codes (departureAirport) I want to compare userFlight and make sure it is one of the possible departureAirports which I have stored in a vector called flights[]. This code obviously isn't working, but is there a similar way to accomplish this?

 if             
        (for (j = 0, j < flights.size, j++)
        {
        (userFlight != flights[j].departAirport)
        })

    {return errorCode};

else
    {//doSomething()};

4 Answers 4

6

If it has a operator< inside which does compare like your condition, how about

if(std::find(flights.begin(), flights.end(), userFlight) != flights.end())
{
    /* found */
}
else
{
    /* not found */
}

Else, if you don't like that, just check if the loop runs through all indices:

size_t i;
for (i = 0, i < flights.size, i++)
{
    if(userFlight == flights[i].departAirport)
        break;
}
if(i < flights.size)
{
    /* found */
}
else
{
    /* not found */
}

But no, a syntax like you want doesn't exist.

Sign up to request clarification or add additional context in comments.

2 Comments

Isn't it the other way aroud? If i < flights.size it was found
Separately, find needs operator== not operator<, and you need a predicate to check .departAirport unless you hack up the Flight class to have a bool operator==(const Airport&) const, which is an ugly idea IMHO - too easy to invoke accidentally in meaningless situations. With a predicate, you can simplify to my answer - std::any_of.
3

The code structure you were aiming for is:

for (j = 0; j < flights.size(); j++)
    if (userFlight == flights[j].departAirport)
        break;

if ( j == flights.size() )   // we got to the end
    return errorCode;

doSomething(j);

However, this is a C-like code style. Not that there is anything wrong with that, but C++ allows for algorithms to be expressed more abstractly (and therefore, easier to read and maintain). IMHO it would be better to use one of the other suggestions such as std::set or std::find_if.

Comments

1

It sounds like you actually want to have a std::set of departing airports.

std::set<std::string> departing_airports = {"DTW", "MKE", "MSP", };
assert(departing_airports.count("DTW") == 1);

Comments

1

Yet another option is std::any_of. Assuming flights contains objects of type Flight:

if (std::any_of(std::begin(flights), std::end(flights),
        [&](const Flight& f) { return userFlight == f.departAirport; }))
    return errorCode;

doSomething();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.