Skip to content

Instantly share code, notes, and snippets.

@thejohnfreeman
Created March 17, 2012 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thejohnfreeman/2065728 to your computer and use it in GitHub Desktop.
Save thejohnfreeman/2065728 to your computer and use it in GitHub Desktop.
Count common elements of sorted C arrays using STL
/* A model of output iterator that will count every time it gets incremented. */
class Counter {
public:
/* Implement a getter if you want. */
int n;
Counter(int n = 0) : n(n) {}
Counter(Counter const& other) : n(other.n) {}
Counter& operator* () { return *this; }
template <typename T>
Counter& operator= (T const&) { return *this; }
Counter& operator= (Counter const& other) { n = other.n; return *this; }
Counter& operator++ () { ++n; return *this; }
Counter& operator++ (int) { return ++(*this); }
};
int M = ...;
int a_followers[M];
int N = ...;
int b_followers[N];
/* After populating and sorting... */
Counter counter;
int overlap = std::set_intersection(
a_followers, a_followers + M,
b_followers, b_followers + N,
counter);
/* Hereafter, counter.n has the count you want. */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment