2014-04-27 40 views
1

我試圖找到2個字符串之間的相交點。我使用下面的代碼:表達式:無序序列

std::string a = "asd", b = "afd"; 

std::string intersect; 
std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(intersect)); 

它編譯成功,但具有下列錯誤運行程序瞬間崩潰後:

enter image description here

任何建議是什麼原因造成這個問題?

+1

錯誤消息告訴你 - 輸入set_intersection需要進行排序。 – joc

回答

2

你應該排序ab它們傳遞給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.

所以,加

std::sort(a.begin(), a.end()); 
std::sort(b.begin(), b.end());