I have a big vector with 24.000 elements like :
(1,1,1,1,3,3,3,3,3,3,5,5,5,...etc)
and I want to check how many same elements are in a row like: 4-6-3..etc I use this code :
static int counter=1;
vector<int>numbers;
for(int n=0;n<numbers.size()-1;n++)
{
if(numbers[n]==numbers[n+1])
{
counter++;
}
else if(numbers[n]!=numbers[n+1])
{
cout<<counter<<endl;
counter=1;
}
}
is there any algorithm that does the same faster;
@rhalbersma basically gave you the right answer. As an addendum, in case you want to rewrite your algorithm in a more standard fashion:
#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 live example.
Also, when the vector is sorted, this will give you better best-case 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 live example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With