Home > Blockchain >  How can I make a vector that checks if there are equal numbers in it?
How can I make a vector that checks if there are equal numbers in it?

Time:12-21

I would like to create a vector that displays if there are equal numbers inside it if there are, an output will have to come out where it says that there are equal numbers if there are not the opposite,

EX: A(2,4,2,7) There are equal numbers

I'm trying any solution but can't figure out how to do it I'm at the beginning of the arrays.

CodePudding user response:

Use std::set, fill it from your vector and compare if the sizes are equal. If not you have duplicates.

std::vector<int> values{1,1,2,3,4,5,5}; 

std::set<int> tmp{values.begin(),values.end()}; 

bool duplicates = (values.size() != tmp.size());

CodePudding user response:

You could try to sort the vector first and then loop through the vector and check if current vector[i] == vector[i 1].

vector<int> yourVector{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
sort(yourVector.begin(), yourVector.end(), greater<int>());

int equalNum = 0;

for(int i = 0; i < yourVector.size()-1; i  )
{
    if(yourVector[i] == yourVector[i 1])
    {
      equalNum  ;
    }
}

if(equalNum > 0)
{
  std::cout << "There are: " << equalNum << "equal numbers" << std::endl;
}else{
  std::cout << "There no equal numbers" << std::endl;
}

This is just some code i just made up haven't tested it.

CodePudding user response:

Might be a good idea to use a map instead:

unordered_map<int, int> numbers;

  numbers[2];
  numbers[4];
  numbers[2];
  numbers[7];

Now you can check how many of each number you have:

cout << "Number of twos: " << numbers[2] << '\n';
  • Related