【问题标题】:How do I compare 2 arrays element by element?如何逐个元素比较 2 个数组?
【发布时间】:2020-07-25 12:28:53
【问题描述】:

Arrays

我想逐个元素地比较 2 个数组并将它们并排打印。 元素比较将是 AND 比较。 (即 0&1=0,0&0=0,1&1=1)

int main()
{
ifstream inFile;
int array1[10][10], array2[10][10];
int rows, cols;
OpenInputFile(inFile);

ReadData(rows, cols, array1, array2, inFile);

cout << "Initial values of the arrays processed" << endl;
cout << string(50,'-') << endl;
cout << setw(2*cols) << left << "Array1";
cout << setw(2*cols) << left << "Array2" << endl;;  
PrintArray(array1, rows, cols),PrintArray(array2, rows, cols);
}

【问题讨论】:

  • 问题是什么?至少显示数组定义。
  • 您对数组的文本表示要好得多。不要链接到可以表示为文本的图像。
  • 您知道如何遍历矩阵,因为您可以打印它们。你知道什么是按位比较。为什么不直接遍历两个数组并对每个元素及其在另一个矩阵中的对应伙伴进行按位比较?
  • 我想将 Array1 中的第 1 行元素 1 与 Array2 中的第 1 行元素 1 进行比较。我正在尝试比较 AND、OR 和 XNOR 逻辑门等数组并打印结果。
  • 尽管使用起来很尴尬,但std::valarray 似乎很合适。它专为执行元素操作而设计,并支持位操作运算符。

标签: c++ arrays algorithm containers bitwise-operators


【解决方案1】:

你来了。

#include <iostream>
#include <iomanip>
#include <functional>
#include <iterator>
#include <algorithm>

int main() 
{
    const size_t N = 4;
    int a1[N] = 
    {
        0b10101, 0b01010, 0b10100, 0b00111   
    };

    int a2[N] = 
    {
        0b11100, 0b00110, 0b11111, 0b10001
    };

    int a3[N];
    int a4[N];

    std::transform( std::begin( a1 ), std::end( a1 ),
                    std::begin( a2 ),
                    std::begin( a3 ),
                    std::bit_and<int>() );

    std::transform( std::begin( a1 ), std::end( a1 ),
                    std::begin( a2 ),
                    std::begin( a4 ),
                    std::bit_or<int>() );


    std::cout << std::hex;                
    for ( const auto &item : a1 )
    {
        std::cout << std::setfill( '0' ) << std::setw( 2 ) << item << ' ';
    }       
    std::cout << '\n';

    for ( const auto &item : a2 )
    {
        std::cout << std::setfill( '0' ) << std::setw( 2 ) << item << ' ';
    }       
    std::cout << '\n';

    for ( const auto &item : a3 )
    {
        std::cout << std::setfill( '0' ) << std::setw( 2 ) << item << ' ';
    }       
    std::cout << '\n';

    for ( const auto &item : a4 ) 
    {
        std::cout << std::setfill( '0' ) << std::setw( 2 ) << item << ' ';
    }       
    std::cout << '\n';

    return 0;
}

程序输出是

15 0a 14 07 
1c 06 1f 11 
14 02 14 01 
1d 0e 1f 17 

编辑:在编辑问题后将一维数组更改为二维数组,然后您可以对源数组中的每对“行”使用显示的算法调用循环。

例如

for ( size_t i = 0; i < N; i++ )
{
    std::transform( std::begin( a1[i] ), std::end( a1[i] ),
                    std::begin( a2[i] ),
                    std::begin( a3[i] ),
                    std::bit_and<int>() );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 2020-08-18
    相关资源
    最近更新 更多