Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ check how many same elements in a row are in a vector

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;

like image 902
Sonicpath Avatar asked May 08 '13 10:05

Sonicpath


1 Answers

@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.

like image 93
Andy Prowl Avatar answered Oct 01 '22 23:10

Andy Prowl