如何比较 c/c++ 中的数组元素?

How do I compare an element of array in c/c++?

int arr[] = {10, 20, 20, 10, 10, 30, 50, 10, 20};

我想比较数组中的每个元素,以便我可以使用 C/C++ 生成相似数字对。

在上面的例子中有三对(10-10、20-20、10-10)。 我想找到给定数组中的对数(即 3)。

任何人都可以帮我逻辑吗?

使用 C 的方法可能不同于使用 C++ 的方法,因为例如在 C++ 中您可以使用标准容器和算法,而在 C 中它们不存在。

所以我将展示一个可以用两种语言实现的解决方案。

给你。该程序是使用 C 编写的,但可以很容易地通过替换 header 并且只有一个语句:输出语句。

将其转换为 C++ 程序。
#include <stdio.h>

int main( void )  
{ 
    int a[] = { 10, 20, 20, 10, 10, 30, 50, 10, 20 };
    const size_t N = sizeof( a ) / sizeof( *a ); 
    size_t total = 0; 

    for ( size_t i = 1; i < N; i++ ) 
    { 
        size_t count = 1; 
        for ( size_t j = 0; j < i; j++ ) 
        { 
            if ( a[i] == a[j] ) ++count; 
        } 

        if ( count % 2 == 0 ) ++total; 
    } 

    printf( "The number of pairs of equal elements is %zu\n", total );

    return 0; 
}

程序输出为

The number of pairs of equal elements is 3

在 C++ 中,您可以使用例如以下使用标准容器 std::mapstd::unordered_map.

的替代方法
#include <iostream> 
#include <map> 

int main()  
{ 
    int a[] = { 10, 20, 20, 10, 10, 30, 50, 10, 20 };
    size_t total = 0; 

    std::map<int, size_t> m; 

    for ( const auto &item : a ) ++m[item]; 

    for ( const auto &item : m ) total += item.second / 2; 

    std::cout << "The number of pairs of equal elements is " << total << '\n'; 

    return 0; 
}

程序输出同上图

The number of pairs of equal elements is 3

这里是 C++ 解决方案。

与弗拉德相同的方法。简单地计算所有值的组并将这个计数器除以 2,因为我们正在查找对。

然后统计总次数:

#include <iostream>
#include <map>
#include <algorithm>
#include <numeric>


int main() {
    // The data
    int arr[] = { 10, 20, 20, 10, 10, 30, 50, 10, 20 };

    // The counter for occurences of one value in the array
    std::map<int, size_t> counter{};

    // Do Count
    for (int i : arr) counter[i]++;

    // Devide all counts by 2. Thats, because we are looking for pairs
    std::for_each(counter.begin(), counter.end(), [](auto& p) { p.second /= 2;});

    // Calculate the overall sum
    size_t pairCounter = std::accumulate(counter.begin(), counter.end(), 0U,
        [](const size_t v, const auto& p) { return v + p.second; });

    std::cout << "\nNumber of pairs: " << pairCounter << "\n";

    return 0;
}