gpt4 book ai didi

c++ - 使用 vector 查找数组中的频率

转载 作者:行者123 更新时间:2023-12-02 18:57:35 27 4
gpt4 key购买 nike

如何更改代码以获取每个元素的计数?使用我的代码一切都好。它有效,但我怎样才能只改变那部分呢?

   #include <iostream>
#include <vector>

void countFreq(int arr[], int n)
{
// Mark all array elements as not visited
std::vector<bool> visited(n, false);

// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++) {

// Skip this element if already processed
if (visited[i] == true)
continue;
// Count frequency
int count = 1;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
visited[j] = true;
count++;
}
}
std::cout<<count<<" ";
}
}

int main()
{
int n;
std::cin>>n;
int arr[n];
for(int i = 0; i < n; i++){
std::cin>>arr[i];
}
countFreq(arr, n);
return 0;
}

关于结果`

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


output 2 2 2 2 2

但我想得到

 output 2 2 2 2 2 2 2 2 2 2

(对于每个元素)

最佳答案

您的函数包含额外的代码,最终会让您感到困惑。 visited 变量本质上是不必要的。从 0 开始计数,并且不对“当前”单元格进行特殊处理,您会发现一些非常简单的代码可以满足您的需要:

void countFreq(int arr[], int n) 
{
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++) {

// Count frequency
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}

std::cout << count << " ";
}
}

关于c++ - 使用 vector 查找数组中的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65970896/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com