I'm trying to find the intersect between 2 strings. I'm using the following code:
std::string a = "asd", b = "afd";
std::string intersect;
std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(intersect));
It compiles successfully, but after running the program instant crashes with the following error:

Any suggestion what is causing this problem?
You should sort a and b first before passing them to std::set_intersection():
template< class InputIt1, class InputIt2, class OutputIt > OutputIt set_intersection( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first ); (1) template< class InputIt1, class InputIt2, class OutputIt, class Compare > OutputIt set_intersection( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp ); (2)Constructs a sorted range beginning at
d_firstconsisting of elements that are found in both sorted ranges[first1, last1)and[first2, last2). The first version expects both input ranges to be sorted withoperator<, the second version expects them to be sorted with the given comparison functioncomp.
So, add
std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());
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