如何获取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 } }

如何获取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 } },c++,for-loop,c++17,mql4,mql5,C++,For Loop,C++17,Mql4,Mql5,问题是,我如何访问for循环索引中的最后一个元素,并让它在每次价格变化时打印第四个索引?MQL5有点类似于C++。我能从C++中携带什么东西吗?< /P> 乙二醇 您只需将i拉到循环外即可: void OnTick() { int i=0; 对于(;i

问题是,我如何访问for循环索引中的最后一个元素,并让它在每次价格变化时打印第四个索引?MQL5有点类似于C++。我能从C++中携带什么东西吗?< /P> 乙二醇


您只需将
i
拉到循环外即可:

void OnTick()
{
int i=0;
对于(;i<5;i++)
{
印刷品(一);
}
//我现在已经超过了最后一个指数
int last=i-1;
}
如果您提前知道循环
5次
,还可以使用以下方法获取最后一个索引:

int last=5-1;

您只需将
i
拉到循环外即可:

void OnTick()
{
int i=0;
对于(;i<5;i++)
{
印刷品(一);
}
//我现在已经超过了最后一个指数
int last=i-1;
}
如果您提前知道循环
5次
,还可以使用以下方法获取最后一个索引:

int last=5-1;

不要使用幻数<代码>5是一个神奇的数字。给它一个有意义的名字,比如
number\u of\u 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
}
constexpr size\u t number\u价格=5;
void OnTick()
{
for(size\u ti=0;i<价格的数量;++i)//for循环函数
{
Print(i);//这将打印循环
}
打印(价格的数量-1);//访问上次价格
}

不要使用幻数<代码>5是一个神奇的数字。给它一个有意义的名字,比如
number\u of\u 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
}
constexpr size\u t number\u价格=5;
void OnTick()
{
for(size\u ti=0;i<价格的数量;++i)//for循环函数
{
Print(i);//这将打印循环
}
打印(价格的数量-1);//访问上次价格
}

无法访问循环范围之外的
i
。无法访问循环范围之外的
i
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
}