21xrx.com
2024-05-20 16:18:13 Monday
登录
文章检索 我的文章 写文章
C++如何求众数
2023-06-23 21:17:58 深夜i     --     --
C++ 求众数 算法 数组 循环

在C++编程中,众数是一个集合中出现最频繁的元素。求众数是一项很重要的任务,它的应用领域涵盖了许多不同的领域。本文将介绍在C++中如何求众数。

1. 统计个数

要求众数,首先需要统计集合中每个元素的出现次数。为了达到这个目的,我们可以定义一个计数器来记录每个元素出现的次数。

例如,假设我们有一个整数集合,其中包含一些整数,我们可以使用以下代码来计算每个数字出现的次数:


#include <iostream>

#include <map>

using namespace std;

int main()

{

  int n;

  map<int, int> count;

  // 输入数字集合

  cout << "Enter the number of elements in the array: ";

  cin >> n;

  int arr[n];

  cout << "Enter the elements: ";

  for(int i = 0; i < n; i++)

  {

    cin >> arr[i];

    count[arr[i]]++; // 记录每个元素出现的次数

  }

  // 输出每个数字出现的次数

  for(auto it = count.begin(); it != count.end(); it++)

  

    cout << it -> first << " occurs " << it -> second << " times." << endl;

  

  return 0;

}

该代码中使用了C++ STL库中的`map`容器,将其用作计数器,键为元素,值为出现次数。使用`count[arr[i]]++`语句,每读入一个元素就将其对应的计数器值加一。

2. 找到最大计数器值对应的元素

经过计数之后,我们需要找到计数器值最大的元素。为此,我们定义一个变量`max_count`,用于记录当前最大的计数器值,并在遍历map时找到满足`it -> second > max_count`的元素。一旦这样的元素被找到,我们更新max_count。

代码如下:


...

  int max_count = 0;

  int mode = 0;

  for(auto it = count.begin(); it != count.end(); it++)

  {

    if(it -> second > max_count)

    

      max_count = it -> second;

      mode = it -> first;

    

  }

  cout << "The mode is: " << mode << endl;

...

该代码中使用了一个变量`mode`,用于记录众数对应的元素。每次遍历map时如果当前计数器值比max_count大,则更新max_count和mode。最终,`mode`的值就是众数的结果。

3. 整合代码

将以上两部分代码组合起来,得到的整体代码如下所示:


#include <iostream>

#include <map>

using namespace std;

int main()

{

  int n;

  map<int, int> count;

  // 输入数字集合

  cout << "Enter the number of elements in the array: ";

  cin >> n;

  int arr[n];

  cout << "Enter the elements: ";

  for(int i = 0; i < n; i++)

  {

    cin >> arr[i];

    count[arr[i]]++; // 记录每个元素出现的次数

  }

  // 输出每个数字出现的次数

  for(auto it = count.begin(); it != count.end(); it++)

  

    cout << it -> first << " occurs " << it -> second << " times." << endl;

  

  // 找出众数

  int max_count = 0;

  int mode = 0;

  for(auto it = count.begin(); it != count.end(); it++)

  {

    if(it -> second > max_count)

    

      max_count = it -> second;

      mode = it -> first;

    

  }

  cout << "The mode is: " << mode << endl;

  return 0;

}

4. 总结

本文介绍了在C++编程中如何通过计数器来求一个集合中的众数。使用STL库中的map容器,将其用作计数器,键为元素,值为出现次数。通过遍历map,找到出现次数最多的元素,即可得到众数。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复