简体   繁体   English

比较C ++中两个数组的2个元素

[英]Compare 2 elements of two arrays in C++

I have two arrays each array has some values for instance: 我有两个数组,每个数组都有一些值,例如:

int a[] =  {1, 2, 3, 4};
int b[] =  {0, 1, 5, 6};

now I need to compare the elements of the array (a) with elements in array (b).. if is there any match the program should return an error or print "error there is a duplicate value" etc.. in the above situation, it should return an error coz a[0] = b[1] because both are have same values. 现在我需要将数组(a)的元素与数组(b)中的元素进行比较..如果有任何匹配程序应该返回错误或打印“错误有重复值”等等。在上述情况,它应该返回一个错误coz a [0] = b [1],因为它们都有相同的值。

How can I do this?? 我怎样才能做到这一点??

If the arrays are this small, I would just do a brute force approach, and loop through both arrays: 如果数组这么小,我只会做一个强力方法,并遍历两个数组:

for (int i=0;i<4;++i)
{
    for (int j=0;j<4;++j)
    {
        if (a[i] == b[j])
        {
            // Return an error, or print "error there is a duplicate value" etc
        }
    }
}

If you're going to be dealing with large arrays, you may want to consider a better algorithm, however, as this is O(n^2). 如果您要处理大型数组,您可能需要考虑更好的算法,因为这是O(n ^ 2)。

If, for example, one of your arrays is sorted, you could check for matches much more quickly, especially as the length of the array(s) gets larger. 例如,如果对某个数组进行了排序,则可以更快地检查匹配,尤其是当数组的长度变大时。 I wouldn't bother with anything more elaborate, though, if your arrays are always going to always be a few elements in length. 但是,如果你的数组总是总是只有几个元素,我就不会为任何更复杂的东西而烦恼。

Assuming both arrays are sorted, you can step them though them like this: 假设两个数组都已排序,您可以像这样对它们进行步骤:

// int array1[FIRSTSIZE];
// int array2[SECONDSIZE];
for(int i=0, j=0; i < FIRSTSIZE && j < SECONDSIZE; ){
    if(array1[i] == array2[j]){
        cout << "DUPLICATE AT POSITION " << i << "," << j << endl;
        i++;
        j++;
    }
    else if(array1[i] < array2[j]){
        i++;
    }
    else{
        j++;
    }
}

This should have linear complexity, but it only works if they're sorted. 这应该具有线性复杂性,但只有在它们被排序时才有效。

The solution for sorted arrays has already been posted. 排序数组的解决方案已经发布。 If the arrays are not sorted, you can build a set (eg std::set or a hash set) out of each and see if the sets are disjoint. 如果数组没有排序,你可以从每个数组中构建一个集合(例如std::set或hash set),看看这些集合是否是不相交的。 You probably have to store value–index pairs in the sets to find out which index was duplicate (and overload the comparison operators appropriately). 您可能必须在集合中存储值索引对,以找出哪个索引是重复的(并适当地重载比较运算符)。 This might give O( n log n ) complexity. 这可能会给出O( n log n )的复杂性。

//v={1,2,3,4};  vector
//v1={1,2,3,4}  vector

  bool f=0;
    if(equal(v.begin(),v.end(),v1.begin()))  //compare two vector, if equal return true
    {
        f=1;
    }

    }
    if(f==1)
        cout<<"Yes"<<endl;
    else cout<<"No"<<endl;

        enter code here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM