开发者

Can't get my array numbers to compare to the other set

I have two arrays that both hold 5 sets of random numbers.

First I display a list of all the numbers in the first array; then I need to add to that list, any number that's not in the first array, and display each of those. To do that, I use another array to put the unique values in to display. I already have a function that displays the current array.

Here's the code where I have the problem:

开发者_StackOverflow中文版
//SIZE is defined in the beginning as 5.

printArray(array1);
 int i, j;
 //For each number in array1, compare each number in array2 to it.
 for(j=0; j<SIZE; j++)
 {
  for(i=0; i<SIZE; i++)
     {
    if(array2[j] != array1[i])//?
    {
     arraySum[j] = array2[j];
     std::cout << arraySum[j] << std::endl;
     break;
    }

     }
 }
 //printArray(arraySum);


It sounds like you're looking for std::set_difference. Example:

std::set_difference(array2, array2 + SIZE, array1, array1 + SIZE,
    std::ostream_iterator<int>(std::cout, "\n"));

Note that array1 and array2 have to be sorted for set_difference.... you can use std::sort on the input arrays if need be.

You'll need to #include <algorithm> for std::set_difference and you'll need to #include <iterator> for std::ostream_iterator.

EDIT: If you want output similar to wheaties' post, you can use std::set_union instead of std::set_difference:

std::set_union(array1, array1 + SIZE, array2, array2 + SIZE,
    std::ostream_iterator<int>(std::cout, "\n"));


I believe this is what you're looking for...

#include <iostream>
int main(){
int i, j, count;
int SIZE = 5;
int array1[] = {1,3,4,5,7};
int array2[] = {0,9,14,5,18};
int arraySum[5];
//For each number in array1, compare each number in array2 to it.
for(j=0; j<SIZE; j++)
{
    count = 0;
    for(i=0; i<SIZE; i++)
    {
        if(array2[j] != array1[i])
        {
        count++;        
        }
    }
    if(count >= 5){
        arraySum[j] = array2[j];
        std::cout << arraySum[j] << std::endl;
    }
}
return 0;
}

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜