快速循环退出后的C++“继续”循环:这是一个好的实践吗?

快速循环退出后的C++“继续”循环:这是一个好的实践吗?,c++,C++,我将编写一个包含循环的函数,稍后可以通过保存的循环环境继续。下面的示例程序是一个良好的实践吗?请参见下面的代码?然而,这个例子中使用了goto:这是好还是坏 我想到的另一种方法是创建一个包含迭代器的类。但处理所有这些迭代器代码似乎更为复杂 示例中的main函数只是演示了如何调用continue-able函数。我的实代码可能包含两个find1函数,比如find1和find2。根据情况,在检查find1和find2结果之间的关系后,我选择哪个函数继续查找过程 -更新- 有人可能会问,我为什么一开始就

我将编写一个包含循环的函数,稍后可以通过保存的循环环境继续。下面的示例程序是一个良好的实践吗?请参见下面的代码?然而,这个例子中使用了goto:这是好还是坏

我想到的另一种方法是创建一个包含迭代器的类。但处理所有这些迭代器代码似乎更为复杂

示例中的main函数只是演示了如何调用continue-able函数。我的实代码可能包含两个find1函数,比如find1和find2。根据情况,在检查find1和find2结果之间的关系后,我选择哪个函数继续查找过程

-更新- 有人可能会问,我为什么一开始就想要这个?是的,这是一个很好的问题:我欢迎不使用可继续循环设计来解决问题的答案。
请原谅我的创造力差,如果没有可继续的循环,我想不出该怎么做。

看起来你正在实施协同程序。虽然我同意协程有时是有用的,但这个案例并不需要它们。你可以有一个存储i和j的类,其中的方法可能被称为*和++来获取下一个元素。Boost还可以帮助过滤/转换迭代器,这样你就可以专注于索引。
#include <iostream>
#include <climits>
using namespace std;

struct IdxPair
{
    int i;
    int j;
};

// finder predicate function: In the real world, this function could be big.
bool pred(int i, int j)
{
    return (i+j == 8);
}

// result generating function: In the real world, this function could be big.
int calc(int i, int j)
{
    return i+j;
}

int find1(bool isFirstLoop)
{
    int i, j;
    static IdxPair toBeContinued;

    if (isFirstLoop) {
        // It's the first time: setup initial values
        i = 0;
        j = 0;
    } else {
        i = toBeContinued.i;
        j = toBeContinued.j;
        goto continueLoop;
    }

    // sample loop:
    // In the real world, it could be more layer of nested loops.
    // The lower/upper limits for i, j could be from functions
    for (i=0; i<10; i++) {
        for (j=0; j<10; j++) {
            cout << "(i, j) = (" << i << ", " << j << ")" << endl;
            if (pred(i,j)) {
                toBeContinued.i = i;
                toBeContinued.j = j;
                return calc(i, j);  // so-called "fast loop exit"
            }
            continueLoop:
            ;
        }
    }
    return INT_MIN;
}


int main()
{
    int result=0;  // Set it to something other than INT_MIN.
    for (result=find1(true); result != INT_MIN; result=find1(false)) {
        cout << "result = " << result << endl;
    }
    cout << "-------------------------------" << endl;
}