c++ STL set difference

2019-01-30 17:22发布

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

10条回答
Anthone
2楼-- · 2019-01-30 18:06

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.

查看更多
▲ chillily
3楼-- · 2019-01-30 18:09

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.

查看更多
该账号已被封号
4楼-- · 2019-01-30 18:09

C++ does not define a set difference operator but you can define your own (using code given in other responses):

template<class T>
set<T> operator -(set<T> reference, set<T> items_to_remove)
{
    set<T> result;
    std::set_difference(
        reference.begin(), reference.end(),
        items_to_remove.begin(), items_to_remove.end(),
        std::inserter(result, result.end()));
    return result;
}
查看更多
虎瘦雄心在
5楼-- · 2019-01-30 18:10

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.

查看更多
登录 后发表回答