Created
November 18, 2014 20:03
-
-
Save dgodfrey206/d6d8d2307e8ec8a534ff to your computer and use it in GitHub Desktop.
consecutive_find() is a function that returns the beginning of a range that contains strictly N consecutive elements. It was part of a SO question that I answered.
This file contains hidden or 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
#include <iostream> | |
#include <vector> | |
#include <algorithm> | |
template <class Iter> | |
Iter consecutive_find(Iter first, Iter last, std::size_t n) | |
{ | |
Iter marker(first), lead(first); | |
std::size_t count(1); | |
while (lead != last) | |
{ | |
lead = std::next(marker); | |
while ((lead != last) && (*marker == *lead)) { ++count; ++lead; } | |
if (count == n) | |
{ | |
if ((lead == last) || !(*lead == *marker)) | |
return marker; | |
} | |
marker = lead; | |
count = 1; | |
} | |
return marker; | |
} | |
void test1() | |
{ | |
std::vector<int> v{1, 2, 2, 2, 3}; | |
auto it = consecutive_find(v.begin(), v.end(), 3); | |
for (int i = 0; i < 3 && it != v.end(); ++i, ++it ) | |
{ | |
std::cout << *it << " "; | |
} | |
std::cout << std::endl; | |
} | |
int main() | |
{ | |
test1(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment