Created
March 17, 2012 22:04
-
-
Save thejohnfreeman/2065728 to your computer and use it in GitHub Desktop.
Count common elements of sorted C arrays using STL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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