简体   繁体   English

在 c++ 中使用嵌套 for 循环需要帮助

[英]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.有 10 个买入出价存储在对象向量中,还有 10 个卖出出价。

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.我想知道我是否可以使用嵌套的 for 循环以及如何检查每个买入出价到所有卖出出价,而不是检查 buybid[0] 价格是否为 < sellbid[i] 价格,然后检查是否 buybid[1] <sellbid[i] 等等。

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).但是,这并不是 N*M(二次时间)最有效的方法。

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.你的复杂度是 Nlogn 的排序,但你只遍历每个向量一次。

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.如果它只是您遇到问题的嵌套 for 循环,那么这应该会有所帮助。 I assume the two arrays are initialised somewhere above the function (though they really should be passed as parameters to the function itself)我假设两个 arrays 在 function 上方的某个地方初始化(尽管它们确实应该作为参数传递给 function 本身)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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