C++学习笔记——set_intersection计算两个字符串交集

来源:互联网 发布:海口优化公司 编辑:程序博客网 时间:2024/05/22 09:12

我们先看一下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> wordsstring 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]中存储的就是那些相同的字符。

由于博主的学识有限,难免会出现错误,欢迎大家在评论区批评,指正,交流,也欢迎大家对博文的内容上的继续补充

0 0
原创粉丝点击