简体   繁体   中英

Return struct element from vector c++

I'm new to C++ and I'm trying to return a struct from a vector of structs by using 2 search criteria.

The function find_city is returning me everything from the defined range, regardless of whether it exists inside the vector of struct.

Here's my code:

struct cityLoc
{
    int hRange;
    int vRange;
    int cityCode;
    string cityName;
};

vector<cityLoc> cl1;

// the vector has already been preloaded with data

// function to return my struct from the vector
cityLoc find_city(int hRange, int vRange)
{
    for (size_t i = 0; i < cl1.size(); i++)
    {
        if ((cl1[i].hRange = hRange) && (cl1[i].vRange = vRange))
        {
            return cl1[i];
        }
    }
}

int main()
{
    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j <= 8; j++)
        {
            cityLoc this_city;
            this_city = find_city(i, j);
            cout << this_city.hRange << ", " << this_city.vRange << endl;
        }
    }
    return 0;
}

Also, aside from this question, I was previously looking into std::find_if and didn't understand it. If I have the following code, what is the output? How do I modify it such that it returns a struct?

auto it = find_if(cl1.begin(), cl1.end(), [](cityLoc& cl) { return cl.hRange == 1; } );

You have a bug here:

    if ((cl1[i].hRange = hRange) && (cl1[i].vRange = vRange))

Those = are assignments, not comparisons! Please enable compiler warnings and you won't be hurt by such obvious typos in future.

std::find_if will return the iterator to the found struct entry if it is successful, std::vector::end() otherwise. So, you should first validate the returning iterator if it is valid or not.

For example:

auto it = std::find_if( cl1.begin(), cl1.end(),
                        [](const cityLoc& cl) { return cl.hRange == 1; } );

if ( it == cl1.end() )
{
    // ERROR: Not found! Return error code etc.
    return -1;
}

// And, if found, process it here...

std::cout << it->hRange << '\n';
std::cout << it->vRange << '\n';

The criteria (predicate) part in std::find_if is a lambda expression .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM