[英]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)。
誰能幫我講邏輯?
The approach using C can differ from the approach using C++ because for example in C++ you can use standard containers and algorithms while in C they are absent.
所以我將展示一個可以用兩種語言實現的解決方案。
給你。 The program is written using C but it is easy can be transformed in a C++ program by substituting the header and only one statement: the output statement.
#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;
}
程序 output 是
The number of pairs of equal elements is 3
在 C++ 中,您可以使用例如以下替代方法,使用標准容器std::map
或std::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;
}
程序 output 與上圖相同。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.