Search code examples
c++stdvectorgoto

How to jump to the end of a for loop, but not leaving it, with goto


I have a function that finds all multiple elements in a vector. If I send in {1,2,3,4,5,1,2,3,3,7} it returns {1,2,3}. My input vector has about 100 to 10000 elements but I expect to have only very few different(!) duplicates; around 1-5%.

Hence I check against my duplicates vector if I already identified an element as occurring multiple times. If so, the function shall go on to the next element if there are any. For this I use a goto.

But I need to have a command after the goto label. Else the compiler complains. Is there any way to avoid the this and keep the goto? I know that I could use some other method, e.g. setting a bool accordingly and using a if(). However I think the goto method is straight forward.

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;
}

Solution

  • You should be able to use a semicolon as a no-op.

        nextElement:
        ;
    }
    

    However, I'm not sure if your method for finding duplicates is efficient. You might be better off sorting the array, then iterating it once. Sorting the vector will group all of the duplicates together. Then you'll simply have to check if the current element is the same as the previous element.