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

本文详细介绍了C++标准库中的set_intersection函数用法,包括两个版本的参数说明及使用示例,特别关注了如何对字符串取交集的操作,并强调了在进行交集运算之前必须对输入范围进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值