在 C++ 中获取数组中数字频率的最快方法是什么?
What is the fastest way to get the frequency of numbers in an array in C++?
我的方法创建了一个 std::map 并通过遍历数组一次用数字及其频率填充它,但我想知道是否有不使用地图的更快方法。
std::unordered_map<int,int>
也可以计算频率,但其 operator[]
具有复杂性 (cppreference):
Average case: constant, worst case: linear in size.
与
相比
Logarithmic in the size of the container.
与 std::map
.
最大数少时可以用数组,直接数:
for (const auto& number : array) counter[number]++;
不可否认,所有这些都已经在评论中说了,所以我还要补充一句:你需要衡量。复杂性仅与渐近运行时有关,而对于给定的输入大小,a std::map
实际上可以更快。
我的方法创建了一个 std::map
std::unordered_map<int,int>
也可以计算频率,但其 operator[]
具有复杂性 (cppreference):
Average case: constant, worst case: linear in size.
与
相比Logarithmic in the size of the container.
与 std::map
.
最大数少时可以用数组,直接数:
for (const auto& number : array) counter[number]++;
不可否认,所有这些都已经在评论中说了,所以我还要补充一句:你需要衡量。复杂性仅与渐近运行时有关,而对于给定的输入大小,a std::map
实际上可以更快。