简体   繁体   English

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

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

i am coding in a language similar to c++ known as mql5.(for mt5 trading platform) they have many similarities... i have a for loop as shown below:我正在使用类似于 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
    }
}

the result of the code above with each price change overtime is:每次价格变化加班时,上面代码的结果是:

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

question is, how do i access the last element in the index of the for loop and get it to print 4th index each time price changes?问题是,我如何访问 for 循环索引中的最后一个元素并在每次价格变化时让它打印第 4 个索引? mql5 is somewhat similar as c++. mql5 有点类似于 c++。 is there anything i can carry from c++?有什么我可以从 C++ 携带的东西吗?

eg例如

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

All you need to do is pull i outside the loop:您需要做的就是将i拉出循环:

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

If you know that you loop 5 times in advance, you could also obtain the last index using:如果您知道您提前循环了5次,您还可以使用以下方法获取最后一个索引:

int last = 5 - 1;

Don't use magic numbers.不要使用幻数。 5 is a magic number. 5是一个神奇的数字。 Give it a meaningful name, like number_of_prices .给它一个有意义的名字,比如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