cesco said:
Hi,
say I have a vector like the following:
vec = [1, 2, 3, 5, 6, 7, 9, 11]
and I'd like to know via a function (for example,
ConsecutiveIntegers(vec, N)) whether there are N consecutive integers.
So, for example, if N=3 then ConsecutiveIntegers(vec, N) should return
true because 1, 2, 3 and 5, 6, 7 are consecutive. If N=4, then
ConsecutiveIntegers(vec, N) should return false because there are no 4
consecutive integers.
Is there in STL an algorithm or is there a combination of algorithms
to accomplish such a task.
Thanks and regards
Francesco
Here is a template function that can be used with forward iterators along
with a overload for a vector. It only makes one pass and will stop once n
consecutive values is impossible. The call to distance might not be optimal
for some containers though.
/****************************/
#include <iostream>
#include <iterator>
#include <vector>
template<typename FwdItr>
bool has_n_consecutive(FwdItr first, FwdItr last, size_t n)
{
typename std::iterator_traits<FwdItr>::difference_type count =
std::distance(first, last);
FwdItr prev;
size_t consec = 0;
for ( ; first != last && consec + count >= n && consec < n;
++first, --count)
{
if (consec == 0 || *first == *prev + 1)
consec++;
else
consec = 1;
prev = first;
}
return consec >= n;
}
template<typename T>
bool has_n_consecutive(std::vector<T> &v, size_t n)
{
return has_n_consecutive(v.begin(), v.end(), n);
}
int main(int, char)
{
bool test_ok = true;
std::vector<int> v;
test_ok &= has_n_consecutive(v.begin(), v.end(), 0);
v.push_back(9);
test_ok &= has_n_consecutive(v.begin(), v.end(), 0);
test_ok &= has_n_consecutive(v.begin(), v.end(), 1);
test_ok &= !has_n_consecutive(v.begin(), v.end(), 2);
v.push_back(1);
v.push_back(2);
v.push_back(3); //3
test_ok &= has_n_consecutive(v.begin(), v.end(), 2);
test_ok &= has_n_consecutive(v.begin(), v.end(), 3);
test_ok &= !has_n_consecutive(v.begin(), v.end(), 4);
test_ok &= !has_n_consecutive(v.begin(), v.end(), 5);
test_ok &= has_n_consecutive(v, 3);
test_ok &= !has_n_consecutive(v, 4);
int ar[] = {9, 1, 2, 3, 4, 9};
test_ok &= has_n_consecutive(ar, ar, 0);
test_ok &= !has_n_consecutive(ar, ar, 1);
test_ok &= has_n_consecutive(ar, ar+(sizeof(ar)/sizeof(ar[0])), 3);
test_ok &= has_n_consecutive(ar, ar+(sizeof(ar)/sizeof(ar[0])), 4);
test_ok &= !has_n_consecutive(ar, ar+(sizeof(ar)/sizeof(ar[0])), 5);
std::cout << "Test " << (test_ok ? "succeded" : "failed") << std::endl;
return 0;
}
/****************************/