将数组的每个元素的计数分配给另一个数组的每个元素,而不使用 count()

Assign the count of every element of an array to each element of another array without count()

本文关键字:元素 数组 count 分配 另一个      更新时间:2023-10-16

基本上我有两个整数数组,S[N],它包含M元素的N个实例,可能包含也可能不包含重复项,以及Sr[M],我想用S[N]的每个元素的实例数量来填充它。例如,如果输入是:

10 5
1 2 3 4 1 5 1 5 2 1

则 N = 10, M = 5,

S[10] = { 1, 2, 3, 4, 1, 5, 1, 5, 2, 1 }
Sr[5] = { 4, 2, 1, 1, 2 } // 4 instances of the number 1, 2 instances of the number 2, 1 instance of the number 3 and so on.

到目前为止,我已经使用了以下代码:

#include <fstream>
#include <algorithm>
using namespace std;
int main()
{
int N, M;
ifstream input;
input.open("aris.in");
input >> N >> M;
int S[N], Sr[M];
for (int i = 0; i < N; ++i)
{
    input >> S[i];
}
input.close();
for (int i = 0; i < M; ++i) {
    Sr[i] = count(S, S+N, i+1);
}
return 0;
}

如何在不使用算法库中的 count() 函数的情况下获得相同的结果?

首先,C++不支持可变长度数组。因此,您必须动态分配数组或使用标准容器std::vector

无论您将使用什么容器,循环都可以如下所示

for ( int i = 0; i < N; ++i ) {
    ++Sr[S[i]-1];
}

当然,最初Sr的每个元素都必须设置为 0。

另外,我认为S的值从1开始。