can anyone help me with a small exercise i have been given from a book. i have to check if numbers enetered into an array have duplicate entries and the following is what i have come up with so far. it compiles and runs but has logic errors which i describe further down.
i know there is probably an easy way to complete this task with better algorithms or function calls however my c++ knowledge is limited so please if possible, offer advice that is simple and uses rudimentry c++ functions etc.
Code:
#include <iostream>
#include <algorithm>
#include <ios>
#include <string>
#include <vector>
#include <iomanip>
int main()
{
std::vector<double> numbers;
double x;
std::cout << "please enter a sequence of numbers" << std::endl;
while(std::cin >> x)
{
numbers.push_back(x);
}
sort(numbers.begin(), numbers.end());
std::vector<double>::size_type size = numbers.size();
int count = 0;
for (int x=0; x!=size; ++x)
{
while(x!=numbers.size())
{
if numbers[0] == numbers[x]
[
++count;
++x;
}
else { ++x;
}
if(numbers[x] == numbers[x+1])
{
++count;
++x;
}else{
++x;
}
++x;
}
std::cout << "the number of duplicate entries is "
<< count << std::endl;
return 0;
}
i am attempting to search the array and check if there a values that are the same for example if the input stream is
1, 2, 3, 3, 4, 5, 2
i hope to get 2 as an answer since the value 2 and 3 are entered twice.
i know that my code is wrong in 2 places but am having trouble on how best to move forward and overcome it.
the first problem if the if statement itself,
if(numbers[x] == numbers[x+1]
is not logical as only 2 numbers adjacent to each other would be compared and the first index would not be compared with an index 4 places down the line.
the other problem is an error that i recieve, its array out of bounds
the code above will compile though, with run time errors however
thanks in advance