[英]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.