将数组的每个元素的计数分配给另一个数组的每个元素,而不使用 count()
Assign the count of every element of an array to each element of another array without count()
基本上我有两个整数数组,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开始。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 如何将元素添加到数组的线程安全函数?
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 输出没有重复元素的动态数组(收缩数组)C++
- 数组中最大的非重复元素
- 数组元素打印的递归方法
- 对字符数组中的元素执行逐位操作
- 缓存std::数组的选定元素,并在c++中自动保持其一致性
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 通过交换元素使数组相同
- 按平均值替换数组中的元素
- 打印矢量数组中的所有元素
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- 如何将元素从向量转移到新数组?
- 如何在向量数组中插入元素?
- 为什么 2 个相同数组的元素彼此相等
- C++ 中的二维整数数组,每行中的元素数量不均匀