I want to check duplicate values in an array

前端 未结 4 1764
梦谈多话
梦谈多话 2021-01-29 09:18

Hi i\'m really glad to know this site to ask question. I have a problem that i made an array. And then i want to check matching values in the array. For example,



        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-29 09:48

    use something like:

    int matchCount = 0;
    for(int i = 0;i < (sizeof(array)/sizeof(int)); i++)
    {
        for( int j=0; j<(sizeof(array)/sizeof(int)); j++)
        {
            if( i != j ) // skip when both indexes point to same location
            {
                if( array[i] == array[j] )
                {
                    matchCount++;
                }
            }
        }
    }
    

    The above is for an array of integers. very similar code for arrays of other sized types

    will count matches twice, so divide final matchCount by 2

提交回复
热议问题