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

时间:2016-01-14 19:20:29

标签: c++ arrays

基本上我有两个int数组,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()函数,如何获得相同的结果?

1 个答案:

答案 0 :(得分:2)

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

您将使用循环的任何容器可以采用以下方式

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

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

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

相关问题