How to effectively compare sets in C ++?

I want to compare two sets using the equal algorithm, but this gives me an error. How can I find out if two sets are equal or not?

 if(equal (a.begin(), a.end(), v.begin(), v.end()) 
+6
source share
2 answers

You can just say a == v , or maybe a.size() == v.size() && a == v . It is as effective as possible. (The latter form with explicit sizing can be better because the installed iterators are not random access.) Update: implies size verification [thanks @juanchopanza!]

+12
source

You are probably calling the std::equal overload using 3 iterators and an additional predicate. So just leave the second end as it is not interpreted as a final iterator, but a predicate that is garbage:

 std::equal(a.begin(), a.end(), v.begin()) 

But since Mark makes his comment in this case, you have to make sure that both container sizes coincide in advance, otherwise you run the risk of running at the end of the second set. Note that C ++ 14 does introduce an overload of std::equal with four iterators (which is exactly what you assumed) and which will depend on size checking implicitly, but it looks like your implementation does not yet support this.

In addition, other answers and comments are true that a == v much simpler, clearer, and streamlined.

+5
source

Source: https://habr.com/ru/post/946807/


All Articles