好的,这是另一个问题"如何在STL中做得更好?" 系列.
我们有两个范围,由first1,last1和first2指定.我们想从[0,last1-first1]中找到不同的i的数量*(first1 + i) == *(first2 + i)
例如:
{a, b, c, d, d, b, c, a}
{a, a, b, c, d, c, c, a}
^ ^ ^ ^
Run Code Online (Sandbox Code Playgroud)
对于这两个范围,答案是4.
有一个很好的STL方式吗?我的意思是最好没有任何手册,而等等.谢谢!
Oli*_*rth 12
std::inner_product(first1, last1, first2, 0, std::plus<T>(), std::equal_to<T>());
Run Code Online (Sandbox Code Playgroud)
UPDATE
康拉德指出在下面的评论这从依靠稍微邪恶隐式转换bool到int.虽然这是完全合法的,但可以避免:
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>);
Run Code Online (Sandbox Code Playgroud)