inline int count_cpp()
{
return count_if(begin(a), end(a), [](int c) {static set<int> s(begin(b), end(b)); return s.find(c) != s.end();});
}
inline int count_c()
{
int c = 0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
if(a[i] == b[j]) {
++ c;
break;
}
}
}
return c;
}
inline int count_map()
{
int c = 0;
map<int, bool> bm;
for (auto i : b) {
bm[i] = true;
}
for (auto i : a) {
if (bm.find(i) != bm.end()) {
++ c;
}
}
return c;
}
[cpp method] Time: 4006 us.
[pure c method] Time: 71019 us.
[map method] Time: 5178 us.
#include <algorithm>
#include <iostream>
using namespace std;
template<typename T, int N, int M>
auto count_match(T(&a)[N], T(&b)[M])
{
size_t match_count = 0;
sort(begin(b), end(b));
for(auto& val : a)
{
if(binary_search(begin(b), end(b), val))
{
++match_count;
}
}
return match_count;
}
int main()
{
int v[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 22};
int v2[] = {0, 22, 33, 5, 4, 8, 9, 0, 13};
std::cout << count_match(v, v2);
cin.get();
}