简体   繁体   中英

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";
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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