c++ STL set difference

后端 未结 10 1688
梦如初夏
梦如初夏 2020-12-23 11:05

Does the C++ STL set data structure have a set difference operator?

相关标签:
10条回答
  • 2020-12-23 11:33

    Yes there is, it is in <algorithm> and is called: std::set_difference. The usage is:

    #include <algorithm>
    #include <set>
    #include <iterator>
    // ...
    std::set<int> s1, s2;
    // Fill in s1 and s2 with values
    std::set<int> result;
    std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
        std::inserter(result, result.end()));
    

    In the end, the set result will contain the s1-s2.

    0 讨论(0)
  • 2020-12-23 11:36

    Yes, there is a set_difference function in the algorithms header.

    Edits:

    FYI, the set data structure is able to efficiently use that algorithm, as stated in its documentation. The algorithm also works not just on sets but on any pair of iterators over sorted collections.

    As others have mentioned, this is an external algorithm, not a method. Presumably that's fine for your application.

    0 讨论(0)
  • 2020-12-23 11:38

    Once again, boost to the rescue:

    #include <string>
    #include <set>
    #include <boost/range/algorithm/set_algorithm.hpp>
    
    std::set<std::string> set0, set1, setDifference;
    boost::set_difference(set0, set1, std::inserter(setDifference, setDifference.begin());
    

    setDifference will contain set0-set1.

    0 讨论(0)
  • 2020-12-23 11:46

    Not an "operator" in the language sense, but there is the set_difference algorithm in the standard library:

    http://www.cplusplus.com/reference/algorithm/set_difference.html

    Of course, the other basic set operations are present too - (union etc), as suggested by the "See also" section at the end of the linked article.

    0 讨论(0)
  • 2020-12-23 11:46

    The chosen answer is correct, but has some syntax errors.

    Instead of

    #include <algorithms>
    

    use

    #include <algorithm>
    

    Instead of

    std::insert_iterator(result, result.end()));
    

    use

    std::insert_iterator<set<int> >(result, result.end()));
    
    0 讨论(0)
  • 2020-12-23 11:55

    can we just use

     set_difference(set1.begin(), set1.end(), set2.begin(). set2,end(),std::back_inserter(result)).
    
    0 讨论(0)
提交回复
热议问题