Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to check if all values in array are different?

Hello I'm trying to check any values that are inputted in an array of any size are different. I am trying to use a nested loop for this code but cannot get a proper if statement to check that each value in the array are different. I'd appreciate any help!

for (unsigned i = 0; i < size; i++)
    for (unsigned k = i + 1; k < size; k++)
        if (arr[i] == arr[k]){
            return false;
        }
return true;

Ok thank you guys for the help your suggestions worked!

like image 263
Pollo Avatar asked Dec 03 '22 16:12

Pollo


2 Answers

Can you sort the arr first?

std::sort(std::begin(arr), std::end(arr));
auto pos = std::adjacent_find(std::begin(arr), std::end(arr));
if (pos != std::end(arr))
    // we have a duplicate
like image 181
Bo Persson Avatar answered Dec 14 '22 23:12

Bo Persson


the first for-loop is wrong. There's a j instead of an i

for (unsigned i = 0; i < size; i++)
 ...
like image 38
Astinog Avatar answered Dec 14 '22 23:12

Astinog