繁体   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