Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression: Sequence not ordered

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:

enter image description here

Any suggestion what is causing this problem?

like image 423
Deepsy Avatar asked Oct 22 '25 20:10

Deepsy


1 Answers

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_first consisting of elements that are found in both sorted ranges [first1, last1) and [first2, last2). The first version expects both input ranges to be sorted with operator<, the second version expects them to be sorted with the given comparison function comp.

So, add

std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());
like image 87
herohuyongtao Avatar answered Oct 24 '25 10:10

herohuyongtao