I have been trying to find the intersection between two std::set in C++, but I keep getting an error.
I created a small sample test for this
#include <iostream> #include <vector> #include <algorithm> #include <set> using namespace std; int main() { set<int> s1; set<int> s2; s1.insert(1); s1.insert(2); s1.insert(3); s1.insert(4); s2.insert(1); s2.insert(6); s2.insert(3); s2.insert(0); set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end()); return 0; }
The latter program does not generate any output, but I expect to have a new set (let's call it s3
) with the following values:
s3 = [ 1 , 3 ]
Instead, I'm getting the error:
test.cpp: In function ‘int main()’: test.cpp:19: error: no matching function for call to ‘set_intersection(std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>)’
What I understand out of this error, is that there's no definition in set_intersection
that accepts Rb_tree_const_iterator<int>
as a parameter.
Furthermore, I suppose the std::set.begin()
method returns an object of such type,
Is there a better way to find the intersection of two std::set
in C++? Preferably a built-in function?
C++ Algorithm set_intersection() function is used to find the intersection of two sorted ranges[first1, last1) and [first2, last2), which is formed only by the elements that are present in both sets.
What is Set in C++? As mentioned above, sets in C++ are the type of STL containers that are used for storing elements in a sorted way. The operations allowed to be performed on sets are insertion and deletion. The elements are internally sorted according to a strict weak ordering in a set type container.
set::size() in C++ STL size() function is used to return the size of the set container or the number of elements in the set container. Return Value: It returns the number of elements in the set container.
You haven't provided an output iterator for set_intersection
template <class InputIterator1, class InputIterator2, class OutputIterator> OutputIterator set_intersection ( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result );
Fix this by doing something like
...; set<int> intersect; set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), std::inserter(intersect, intersect.begin()));
You need a std::insert
iterator since the set is as of now empty. We cannot use std::back_inserter
or std::front_inserter
since set doesn't support those operations.
Have a look at the sample in the link: http://en.cppreference.com/w/cpp/algorithm/set_intersection
You need another container to store the intersection data, below code suppose to work:
std::vector<int> common_data; set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(), std::back_inserter(common_data));
If 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