leticia m
leticia m

Reputation: 9

Count number of times element is inserted into vector

I implemented a code that counts the number of times an element is inserted into the vector within the range N, and then I print the number that appeared the most and how many times it appeared. But my account is always returning strange values. For example, if I enter the number "123" four times, the cont returns "6". I can not see the error

#include <iostream>
#include <vector>
using namespace std;

int main() {

int N,cont, i, j, elem,a;
vector<int> voto;

cin >> N;
cout << "Enter the values ​​of the vector: "<< endl;
while(N!=0) {
  cin >> elem;
  voto.push_back(elem);
  N--;
  }
  cont = 0;
int s = voto.size();
for(i = 0; i < s; i++){
    for(j = i + 1; j< s; j++) {
      if(voto[j] == voto[i])
      cont++;
      else
      break;

      a = voto[i];

    }
}

cout << "The most voted was" << a << "with"<<cont<<"vote";
return 0;
}

Upvotes: 0

Views: 248

Answers (3)

Jarod42
Jarod42

Reputation: 217810

With std::map and std::max_element, you can do:

int N;
std::map<int, std::size_t> m;

std::cin >> N;
std::cout << "Enter the values of the vector: "<< std::endl;
while (N != 0) {
    int elem;
    std::cin >> elem;
    ++m[elem];
    N--;
}
auto it = std::max_element(m.begin(), m.end(),
                           [](const auto& lhs, const auto& rhs){
                                return lhs.second < rhs.second;
                           });

std::cout << "The most voted was " << it->first << " with " << it->second << " votes";

Demo

Upvotes: 0

Damien
Damien

Reputation: 4864

The procedure that you tried has a complexity O(n^2). You can improve efficiency while simplifying the programme:

1 Sort the vector (std::sort): complexity O(n logn)
2 Loop on the sorted vector to count consecutive duplicates : complexity O(n)

As mentioned in comments, if you are allowed, using std::mapwill simplify the programme further, with still a complexity O(n logn)

Upvotes: 0

theSpacebaker
theSpacebaker

Reputation: 11

There's a couple problems with your code.

  • cont is never getting set back to 0

  • If the duplicates in your vector are not next to each other, you are breaking

  • If the most frequent duplicates are at the beginning they are being overwritten by the next set of duplicates

To solve these issues you need a maxCont as well as your cont. When counting duplicates compare the current cont to maxCont, if greater replace it.

Upvotes: 1

Related Questions