C++ 比较C++中两个数组的2个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3151801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare 2 elements of two arrays in C++
提问by SolidSnake
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) 中的元素进行比较.. 如果有任何匹配项,程序应返回错误或打印“错误存在重复值”等.. 在上述情况下,它应该返回错误因为 a[0] = b[1] 因为两者具有相同的值。
How can I do this??
我怎样才能做到这一点??
回答by Reed Copsey
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.
例如,如果您的一个数组已排序,您可以更快地检查匹配项,尤其是当数组的长度变大时。不过,如果您的数组的长度总是几个元素,我就不会费心做更复杂的事情了。
回答by Brendan Long
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.
这应该具有线性复杂性,但只有在对它们进行排序时才有效。
回答by Philipp
The solution for sorted arrays has already been posted. If the arrays are not sorted, you can build a set (e.g. std::set
or a hash set) out of each and see if the sets are disjoint. 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(nlog n) complexity.
排序数组的解决方案已经发布。如果数组未排序,您可以std::set
从每个数组中构建一个集合(例如或散列集合)并查看这些集合是否不相交。您可能必须在集合中存储值-索引对以找出哪个索引是重复的(并适当地重载比较运算符)。这可能会导致 O( nlog n) 复杂度。
回答by asad_IT
//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