具有STL的两个序列中的匹配数 [英] number of matches in two sequences with STL
问题描述
好的,这里是另一个问题的如何做到更好的STL?系列。
OK, here is yet another question of the "How to do it better in STL?" series.
我们有两个范围,由first1,last1和first2指定。我们想从[0,last1-first1]找到不同i的数字,使得 *(first1 + i)== *(first2 + i)
We have two ranges, designated by first1, last1, and first2. We want to find the number of different i's from [0, last1-first1] such that *(first1 + i) == *(first2 + i)
例如:
{a, b, c, d, d, b, c, a}
{a, a, b, c, d, c, c, a}
^ ^ ^ ^
对于这两个范围,答案是4。
For these two ranges the answer is 4.
有很好的STL方法吗?
Is there a good STL way to do it? I mean preferrably without any manual for's, while's etc. Thanks!
推荐答案
std::inner_product(first1, last1, first2, 0, std::plus<T>(), std::equal_to<T>());
UPDATE
Konrad在下面的注释中指出,这依赖于从 bool
到 int
的一些非法的隐式转换。虽然这是完全合法的,但是可以这样避免:
Konrad has pointed out in the comments below that this relies on slightly nefarious implicit conversion from bool
to int
. Whilst this is completely legal, it can be avoided thus:
template <typename T>
int match(const T &a, const T &b) { return (a == b) ? 1 : 0; }
std::inner_product(first1, last1, first2, 0, std::plus<T>(), match<T>);
这篇关于具有STL的两个序列中的匹配数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!