简体   繁体   中英

what is the alternative to set_difference in c++

I have two sets .they have some common elements(sets have strings as thier elements)

like : set1 has elements

"1-2","1-1","3-4"

set2 has elements

"1-2","1-3","3-4"

i want take out the values "1-1" into one set and value "1-3" into another. i know set_difference will do the job for me.But some how i am facing some problems with set_ifference .please check here

Is there any alternative to using set_difference achieving the same reults?

The alternative would be to roll your own, as Kerrek SB did in his answer to your question .

That said, it would be far better to understand and to solve the problem you have with std::set_difference() , rather than working around it.

For instance, were I getting long compiler errors involving templates on the line containing set_difference , I would break this up into a small series of separate, simple statements, which will make pinpointing the error much easier:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <set>
#include <string>

int main()
{
    typedef std::set<std::string> set_of_strings;
    set_of_strings s1, s2, result;

    s1.insert("1-2");
    s1.insert("1-1");
    s1.insert("3-4");

    s2.insert("1-2");
    s2.insert("1-3");
    s2.insert("3-4");

    // Temporary variables for debugging only
    set_of_strings::iterator s1_begin = s1.begin();
    set_of_strings::iterator s1_end = s1.end();
    set_of_strings::iterator s2_begin = s2.begin();
    set_of_strings::iterator s2_end = s2.end();
    set_of_strings::iterator result_end = result.end();
    std::insert_iterator<set_of_strings> result_inserter = std::inserter(result, result_end);

    std::set_difference(s1_begin, s1_end,
                        s2_begin, s2_end,
                        result_inserter);

    std::copy(result.begin(),
              result.end(),
              std::ostream_iterator<std::string>(std::cout, "\n"));
}

The compiler would then check that each of set_difference 's five parameters is of the type that it expects and would allow me to see quite quickly which of them is causing the issue because they're all declared in separate statements.

Once I'd solved the issue, I'd refactor to remove the unnecessary variables, of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM