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