std::relational operators (set) The equality comparison ( operator== ) is performed by first comparing sizes, and if they match, the elements are compared sequentially using operator== , stopping at the first mismatch (as if using algorithm equal ).
Python Set | difference()The difference between the two sets in Python is equal to the difference between the number of elements in two sets. The function difference() returns a set that is the difference between two sets. Let's try to find out what will be the difference between two sets A and B.
Yes, operator==
is correctly defined for all standard containers (except the unordered containers - based on 23.2.5.2 of the standard), and will generally do a lexicographic comparison. See for example here. The relevant quote:
Checks if the contents of lhs and rhs are equal, that is, whether lhs.size() == rhs.size() and each element in lhs has equivalent element in rhs at the same position.
Since std::set
is an ordered container, any set with the same size and same elements (given the comparators are the same) will necessarily have them in the same position, hence will compare equal.
There are several set operations in C++ standard library header <algorithm>
.
std::set_difference
gives those elements that are in set 1 but not set 2.
std::set_intersection
gives those elements that are in both sets.
std::set_symmetric_difference
gives those elements that appear in one of the sets but not both.
std::set_union
gives those elements that are in either set 1 or set 2.
The algorithms above can also be applied to STL containers other than std::set
, but the containers have to be sorted first (std::set
is sorted by default).
Another way would be this:
template<typename Set>
bool set_compare(Set const &lhs, Set const &rhs){
return lhs.size() == rhs.size()
&& equal(lhs.begin(), lhs.end(), rhs.begin());
}
Inspired from the elegant answer here.
C++11 standard on ==
for std::set
Others have mentioned that operator==
does compare std::set
contents and works, but here is a quote from the C++11 N3337 standard draft which I believe implies that.
The quote is exactly the same as that for std::vector
which I have interpreted in full detail at: C++: Comparing two vectors
As a short summary to avoid duplication with that other answer:
equal()
for operator==
equal
and explicitly shows that it iterates over both containers comparing the elements of eachIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With