@rhalbersma basically gave you the correct answer. In addition, if you want to rewrite your algorithm in a more standard way:
#include <algorithm> #include <vector> #include <iterator> #include <functional> #include <iostream> int main() { std::vector<int> v { 1, 1, 2, 3, 3, 5, 5, 5 }; // or whatever... auto i = begin(v); while (i != end(v)) { auto j = adjacent_find(i, end(v), std::not_equal_to<int>()); if (j == end(v)) { std::cout << distance(i, j); break; } std::cout << distance(i, j) + 1 << std::endl; i = next(j); } }
Here is a living example .
Also, when the vector is sorted, this will give you the best at best complexity:
#include <algorithm> #include <vector> #include <iterator> #include <iostream> int main() { std::vector<int> v { 1, 1, 2, 3, 3, 5, 5, 5 }; // must be sorted... auto i = begin(v); while (i != end(v)) { auto ub = upper_bound(i, end(v), *i); std::cout << distance(i, ub) << std::endl; i = ub; } }
Here is a living example .
source share