简体   繁体   English

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

[英]Comparing the elements of two integer arrays in c++

I have two integer arrays 我有两个整数数组

#include<iostream> 
using namespace std;
int comparetwoarrays( int array1[], int array2[], int ARRAY_SIZE1, int ARRAY_SIZE2 )

int main ()
{
    int const ARRAY_SIZE = 500;
    int const ARRAY_SIZE = 10;
    int array1[ARRAY_SIZE];
    int array2[ARRAY_SIZE2];
    comparetwoarrays( array1, array2, ARRAY_SIZE1, ARRAYSIZE2 )
}

int comparetwoarrays( int array1[], int array2[], int ARRAY_SIZE1, int ARRAY_SIZE2 )
{
    int holdsAlike[10] = {0};
    for( int g = 0; g < ARRAY_SIZE2; g++ )
    {
        for ( int t = 0; t < ARRAY_SIZE2; t++ )
        {
            if ( array2[g] == array1[t])
            {
                 holdsAlike[g] = array2[g];
                 cout<<holdsAlike[g];
            }
            for( int w = 0; w < ARRAY_SIZE2; w++ )
            {
                 if( holdsAlike[w] != 0 )
                 cout<<holdsAlike[w];
            }
        }
    }

I want to compare the elements of both arrays, and print out the value and the index of the element. 我想比较两个数组的元素,并打印出元素的值和索引。 Not sure how to go about getting this done. 不确定如何完成此操作。 Any insight would be appreciated. 任何见识将不胜感激。

Code what you want. 编写所需的代码。 It may be like this: 可能是这样的:

#include <iostream>

using std::cout;

int comparetwoarrays( const int array1[], const int array2[], int array_size1, int array_size2 );

int main ()
{
    int const ARRAY_SIZE1 = 500;
    int const ARRAY_SIZE2 = 10;
    int array1[ARRAY_SIZE1] = {0};
    int array2[ARRAY_SIZE2] = {0};

    // set values to the arrays

    comparetwoarrays( array1, array2, 10, ARRAY_SIZE2 );
}

void comparetwoarrays( const int array1[], const int array2[], int array_size1, int array_size2 )
{
    for( int g = 0; g < array_size2; g++ )
    {
        for ( int t = 0; t < array_size1; t++ )
        {
            if ( array2[g] == array1[t])
            {
                if (g == t)
                {
                    cout << "got \"" << array2[g] << "\" at index " << g << "\n";
                }
                else
                {
                    cout << "got value = " << array2[g] << ", index on array2 = " << g <<", index on array1 = " << t << "\n";
                }
            }
        }
    }
}

If you want to print only elements both index and value are matched: 如果只想打印元素,则索引和值都匹配:

void comparetwoarrays( const int array1[], const int array2[], int array_size1, int array_size2 )
{
    for( int g = 0; g < array_size1 && g < array_size2; g++ )
    {
        if ( array2[g] == array1[g])
        {
            cout << "got \"" << array2[g] << "\" at index " << g << "\n";
        }
    }
}

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

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