如何使用goto跳转到for循环的末尾,但不要离开它

dan*_*ani 0 c++ goto stdvector

我有一个函数,可以在向量中找到所有多个元素.如果我发送{1,2,3,4,5,1,2,3,3,7}它返回{1,2,3}.我的输入向量有大约100到10000个元素,但我希望只有很少的不同(!)重复; 约1-5%.

因此,如果我已经多次识别出一个元素,我会检查我的重复矢量.如果是,则该函数将继续执行下一个元素(如果有).为此我用了一个goto.

但是我需要在之后有一个命令goto label.否则编译器会抱怨.有没有办法避免这个并保持goto?我知道我可以使用其他方法,例如相应地设置bool并使用if().不过我认为goto方法很简单.

vector<int> findDublicates(vector<int> const& v) {
    // e.g. {1,2,3,4,5,1,2,3,7} -> {1,2,3}
    vector<int> dublicates;
    for (auto it(v.begin()); it != v.end() - 1;
         ++it) { // go through each element except the last
        for (auto const& i :
             dublicates) { // check if this is already a known dublicate
            if (i == *it)
                goto nextElement; // if so, goto the next element in v
        }
        for (auto it2(it + 1); it2 != v.end();
             ++it2) { // else compare it with the "not checked" elements in v
            if (*it == *it2) { // if a dublicate is found, keep it
                dublicates.emplace_back(*it);
                break; // check the next element in v; could also use goto
                       // nextElement
            }
        }
    nextElement:
        cout << " "; // if I remove cout it won't compile: "expected
                     // primary-expression before '}' token"
    }
    return dublicates;
}
Run Code Online (Sandbox Code Playgroud)

Mr.*_*ama 5

您应该能够使用分号作为无操作.

    nextElement:
    ;
}
Run Code Online (Sandbox Code Playgroud)

但是,我不确定您查找重复项的方法是否有效.您可能最好对数组进行排序,然后迭代一次.对矢量进行排序会将所有重复项组合在一起.然后你只需要检查当前元素是否与前一个元素相同.