简体   繁体   中英

need help using nested for loops in c++

i am working on a double auctioneer simulator and i need a method that checks the buy and sell bids to see if the buy price is < the sell price. there is 10 buy bids which are stored in a vector of objects and 10 sell bids.

below i have attached my code of my method. i know i can have several loops that checks one buy bid to all sell bids.

void match()
{
    for (int i=0;i<buyBid.size();i++)
    { 
        if (buyBid[0].price <= sellBid[i].price)
        {
            matchedBids.push_back(buyBid[0]);
            matchedBids.push_back(sellBid[i]);
            clearingPrice = (buyBid[0].price+sellBid[i].price)/2;
            cout <<clearingPrice<<endl;
        }   
        else
        {
            unmatchedBuyBids.push_back(buyBid[0]);
            unmatchedSellBids.push_back(sellBid[i]);
        }
    }       
}   

i would like to know if i can use nested for loops and how i can, to check each buy bid to all sell bids instead of checking if buybid[0] price is < sellbid[i] price and then checking if buybid[1] < sellbid[i] and so on.

There are some missing details here. Can any buy bid match against and sell bid once the condition is met? You could use two nested loops to check one price against the other and skip the indices of prices that have already been match (or the equivalent). However, this isn't the most efficient at N*M (quadratic time).

You could sort the prices and progressively walk the respective vectors, matching prices along the way. Your complexity is Nlogn for the sorts, but you only traverse each vector once.

for(int i = 0; i < sellBid.size(); ++i)
{
    for(int j = 0; j < buyBid.size(); ++j)
    {
        if (buyBid[j].price <= sellBid[i].price)
        {
            matchedBids.push_back(buyBid[j]);
            matchedBids.push_back(sellBid[i]);
            clearingPrice = (buyBid[j].price + sellBid[i].price) / 2;
            cout << clearingPrice << endl;
        }   
        else
        {
            unmatchedBuyBids.push_back(buyBid[j]);
            unmatchedSellBids.push_back(sellBid[i]);
        }
    }
}

If it is just a nested for loop you are having trouble with, then this should help. I assume the two arrays are initialised somewhere above the function (though they really should be passed as parameters to the function itself)

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