簡體   English   中英

如何獲取for循環中的最后一個索引

[英]How to get the last index in a for loop

我正在使用類似於 c++ 的語言進行編碼,稱為 mql5。(對於 mt5 交易平台)它們有很多相似之處...我有一個 for 循環,如下所示:

void OnTick()  // this functon basically executes the code after every price change.
{
   for (int i = 0; i<5; i++)  //the for loop function
    {
     Print(i);  //this prints the loop
    }
}

每次價格變化加班時,上面代碼的結果是:

13:27:18.706    0
13:27:18.706    1
13:27:18.706    2
13:27:18.706    3
13:27:18.706    4

13:27:18.900    0
13:27:18.900    1
13:27:18.900    2
13:27:18.900    3
13:27:18.900    4

問題是,我如何訪問 for 循環索引中的最后一個元素並在每次價格變化時讓它打印第 4 個索引? mql5 有點類似於 c++。 有什么我可以從 C++ 攜帶的東西嗎?

例如

13:27:18.706    4
13:27:18.900    4

您需要做的就是將i拉出循環:

void OnTick()
{
   int i = 0;
   for (; i < 5; i++)
   {
     Print(i);
   }
   // i is now one past the last index
   int last = i - 1;
}

如果您知道您提前循環了5次,您還可以使用以下方法獲取最后一個索引:

int last = 5 - 1;

不要使用幻數。 5是一個神奇的數字。 給它一個有意義的名字,比如number_of_prices

constexpr size_t number_of_prices = 5;

void OnTick()
{
    for (size_t i = 0; i < number_of_prices; ++i)  //the for loop function
    {
        Print(i);  //this prints the loop
    }
    Print(number_of_prices - 1); // access last price
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM