简体   繁体   English

如何比较 C++ 上两个 arrays 上的元素

[英]How to compare the elements on two arrays on C++

A c ++ problem where I have to determine if the user hit the target.一个 c ++ 问题,我必须确定用户是否击中目标。 After entering the coordinates of where enemies coulb be, the user then enters more coordinates and I must compare them, print YES if the element[i] of the attacks matches any element of enemies [n].输入敌人可能所在的坐标后,用户输入更多坐标,我必须比较它们,如果攻击的元素 [i] 与敌人 [n] 的任何元素匹配,则打印 YES。 I know that I'm comparing positions and not elements that's why it's not working but I'm lost.I also tried to solve it by making only one array but it felt better this way.我知道我在比较位置而不是元素,这就是为什么它不起作用但我迷路了。我也尝试通过只制作一个数组来解决它,但这样感觉更好。

    #include <iostream>
    using namespace std;

    int main()
    {
    int n, k, b;
    int enemies[];
    int attacks[];
    
    cin>>n;
    for (int i=0; i<n; i++) {
        cin>>b;
        enemies[i]=b;
    }
    
    cin>>k; 
    for (int i=0; i<k; i++) {
        cin>>b;
        atacks[i]=b;
    }
    
    for(int i=0; i<k; i++){
       if(atacks[i]==enemies[i]){
                cout<<"YES"<<endl;
       }
       else{
           cout<<"NO"<<endl;
       }
    
    return 0;
}

Your code likely doesn't work because this line:您的代码可能不起作用,因为这一行:

if(atacks[i]==enemies[i])

requires that matching attack and enemy should have the same index in their arrays.要求匹配的attackenemy在其 arrays 中应具有相同的索引。

As suggested in the comments, you need to iterate over ALL enemies for EACH attack , which is "O(n*k) solution"正如评论中所建议的,您需要为 EACH attack遍历所有enemies ,这是“O(n*k) 解决方案”

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

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