C++學習筆記——set_intersection計算兩個字符串交集

我們先看一下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.

所以在intersection前務必對取交集的對象a和b進行sort

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

具體說一下對string取交集的兩種操作
方法1:

//vector<string> words
string int_sec;          set_intersection(words[i].begin(),words[i].end(),words[j].begin(),words[j].end(),back_inserter(int_sec));

//得到的string int_sec爲交集的字符

方法2:

 char int_sec[100000];
 char*int_sec_end=set_intersection(words[i].begin(),words[i].end(),words[j].begin(),words[j].end(),int_sec);
 // int_sec_end-int_sec就是個數,並且c[0]到c[int_sec_end-int_sec-1]中存儲的就是那些相同的字符。

由於博主的學識有限,難免會出現錯誤,歡迎大家在評論區批評,指正,交流,也歡迎大家對博文的內容上的繼續補充

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章