如何获取for循环中的最后一个索引

问题描述

我正在使用类似于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
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...