如何用STL中的set_intersection函数求出集合A和集合B相同的字符串(string)???
这是C++自带一个整数的 set_intersection 例子
#include <algorithm>
#include <set>
#include <iostream>
using namespace std;
int main()
{
int a1[10] = {1,3,5,7,9,11}; //集合A
int a3[4] = {3,5,7,8}; //集合B
set <int, less <int> > odd(a1+0, a1+6),
result, small(a3+0,a3+4);
insert_iterator <set <int, less <int> > >
res_ins(result, result.begin());
cout < < "The result of: " < < endl < < "{ ";
copy(small.begin(),small.end(),
ostream_iterator <int,char> (cout, " "));
cout < < "} intersection { ";
copy(odd.begin(),odd.end(),
ostream_iterator <int,char> (cout, " "));
cout < < "} = " < < endl < < "{ ";
set_intersection(small.begin(), small.end(),
odd.begin(), odd.end(), res_ins);
copy(result.begin(),result.end(),
ostream_iterator <int,char> (cout, " "));
cout < < "} " < < endl < < endl;
return 0;
}
程序输出结果:
The result of:
{3 5 7 8 } intersection {1 3 5 7 9 11 } =
{3 5 7 } //集合A 集合B 的交集
如何用STL中的set_intersection函数求出集合A和集合B相同的字符串(string),
若不相同的的字符串, 并返回两串中字母相同的个数(count)?我不太懂STL!
如 集合A 集合B
ABC ABC
ABB AAC
运算后
第一组:
集合A 集合B 相同字符个数(count)
ABC ABC (ABC) 3个
AAC (A C) 2个
第二组:
集合A 集合B 相同字符个数(count)
ABB ABC (AB)2个
AAA (A )1个
C++ 自带的模板。
template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator set_intersection (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result)
{
while (first1 != last1 && first2 != last2)
{
if (*first1 < *first2)
++first1;
else if (*first2 < *first1)
++first2;
else
{
*result++ = *first1++;
++first2;
}
}
return result;
}
各位大侠,能帮我改改吗?谢谢!!!
[解决办法]
下面是一个例子,字符串存在数组中:
char *a = "ABC ";
char *b = "AAC ";
char c[256]; // 足够大,取min(strlen(a), strlen(b))即可
char* c_end = set_intersection(a, a+strlen(a), b, b+strlen(b), c);
cout < < "相同字符个数个数为 " < < (c_end-c) < <endl;
// c_end-c就是个数,并且c[0]到c[c_end-c-1]中存储的就是那些相同的字符。
iterator没什么可怕的,不过没学过STL,就先把它看成在数组上游走的指针好了。