How to store set difference s1-s2 in s1 without temporary set?

Viewed 306

Does STL already contain any simple method or algorithm for storing the difference between to sets set1 and set2 directly in set1, without the need for a temporary set variable?

The sample code below shows some alternatives that I already have tried (which did not work) and the solution with a temporary set tmp (which I want to avoid):

int _tmain(int argc, _TCHAR* argv[])
{
    std::set<int> set1, set2;

    set1.insert(1); set1.insert(2); set1.insert(3); set1.insert(4); set1.insert(5);
    set2.insert(4); set2.insert(6);

    // NONE OF THE FOLLOWING ALTERNATIVES DID WORK:
    // a: // set1.erase(set2.end(), set2.begin());
    // b: // std::set_difference(set1.begin(), set1.end(), 
    //                set2.begin(), set2.end(), set1.begin());
    // c: // std::remove_if(set1.begin(), set1.end(), 
    //                [set2](int i){return set2.find(i) != set2.end();} );

    // Complicated version, for which I am trying to find something simpler:
    std::set<int> tmp;
    std::set_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(tmp, tmp.end()));
    set1.clear();
    std::copy(tmp.begin(), tmp.end(), std::inserter(set1, set1.end()));

    // Print result: // Expect 1 2 3 5
    std::cout << "set1: ";
    for (auto it=set1.begin(); it != set1.end(); it++)
    {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

I am looking for a solution that does not require C++11 (except the few C++11 constructs allowed in Visual Studio 2010).

3 Answers
Related