If values are same in array?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Beginner1
    New Member
    • Feb 2007
    • 16

    If values are same in array?

    Hello,

    Can anybody help me to write a nice code to find out if all values in array (vector or map) are the same.

    int x[5] = {'1', '2, '3', '1', '2'}

    int y[3] = {'1', '1, '1'} or int y[3] = {'3', '3', '3'}

    I need to write a function which will return true if all values are identical in given array (case with X[5]) and false otherwise (case with Y[3]);

    bool isSameValue(int *array)
    {

    }

    Thanks in advanced.
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    Code:
    bool isSameValue(int *array)
    {
    
    }
    Better make that

    Code:
    bool isSameValue(int *array, int arraySize)
    {
    
    }
    The function can't do much with an array unless it knows how big it is. If you pass a function an array parameter, it usually has to have a size parameter to go along with it.

    In your function, you can just use a for loop to go through all the values in the array and check if they are the same as the first value in the array. If a single value doesn't match, you get out of the function right away with a return statement. But if you get all the way through the loop without any mismatches, you can then return true. It shouldn't be difficult to write this function.

    Hope this helps.

    Comment

    Working...