kir*_*off 12 c c++ loops break
关于C++代码的简单问题:
for(int i=0;i<npts;i++)
{
for(int j=i;j<2*ndim;j++)
{
if(funcEvals[i]<bestListEval[j])
{
bestListEval[j] = funcEvals[i];
for(int k=0;k<m_ndim;k++)
bestList[j][k] = simplex[i][k];
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想确保这一点
double **simplex最多插入一次double **bestListbreak这里的实例突破了第二个(内部)for循环.是这样的吗?
Ser*_* K. 32
C++中的break语句将脱离直接放置break的for或switch语句.它打破了最内层的结构(循环或开关).在这种情况下:
for(int i=0;i<npts;i++)
{
for(int j=i;j<2*ndim;j++)
{
if(funcEvals[i]<bestListEval[j])
{
bestListEval[j] = funcEvals[i];
for(int k=0;k<m_ndim;k++)
bestList[j][k] = simplex[i][k];
break;
}
}
// after the 'break' you will end up here
}
Run Code Online (Sandbox Code Playgroud)
C++中没有办法让任何其他循环中断目标.为了打破父循环,您需要使用其他一些独立的机制,如触发结束条件.
此外,如果要退出多个内循环,可以将该循环提取到函数中.在C++ 11中,可以使用lambda来就地执行它 - 因此不需要使用goto.
在breakC++中声明将跳出的for或switch在其中的发言break被直接放置.在这种情况下,它将突破for (int j = ...循环.
C++中没有办法break定位任何其他循环.为了打破父循环,您需要使用其他一些独立的机制,如触发结束条件.
// Causes the next iteration of the 'for (int i ...' loop to end the loop)
i = npts;
// Ends the 'for (int j ...' loop
break;
Run Code Online (Sandbox Code Playgroud)