Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created November 18, 2014 20:03
Show Gist options
  • Save dgodfrey206/d6d8d2307e8ec8a534ff to your computer and use it in GitHub Desktop.
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.
#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