【问题标题】:calculating occurrences of values in an input stream计算输入流中值的出现次数
【发布时间】:2018-07-11 11:57:18
【问题描述】:

我是一名正在学习编程的大学生。给我们的问题陈述之一是:

用户输入一个整数 n,后跟 n 个不同的整数。在不使用数组或字符串的情况下,找出输入流中出现次数最多的数字。

我们需要使用 simplecpp 包,它基本上是比标准 c++ 更简单的命令。例如,我们编写 repeat(n) 来获得一个具有 n 次迭代的 for 循环。

我能做些什么来解决这个问题?

我想创建一个像

这样的数字
10101010[number]10101010[number2]...

存储输入然后拆分,但这无法解决问题。 我们不允许使用诸如while循环或字符串操作之类的东西来解决问题。我能想到的唯一解决方案是使用字符串方法然后操作字符串,但显然这是不允许的。 有什么方法可以解决这个问题以及其他无法将输入存储在数组中的问题?

【问题讨论】:

  • 请自己试一试,并附上Minimal, Complete, and Verifiable example
  • 我不认为你可以通过这些限制来解决这个问题,除非输入具有某种结构 - 例如,如果连续输入所有相等的整数。 (除非你被允许使用std::map 或类似的,或者滚动你自己的表类。)
  • 您打算如何从没有循环的流中读取动态数量的 anything
  • 我们可以使用 for 循环。不允许其他循环

标签: c++ loops counting


【解决方案1】:

假设您被允许使用普通流媒体,以及其他未被明确禁止的 std:: 标头

#include <iostream>
#include <map>
#include <algorithm>

using counter = std::map<int, int>;
using element = std::map<int, int>::const_reference;

bool compare_second(element lhs, element rhs)
{
    return lhs.second < rhs.second;
}

int main()
{
    counter data;
    int n = 0;
    std::cin >> n;
    for (int i = 0; i < n; ++i)
    {
        int current = 0;
        std::cin >> current;
        data[current]++;
    }

    if (n > 1)
    {
        std::cout << std::max_element(data.begin(), data.end(), compare_second)->second;
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 2018-07-12
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    相关资源
    最近更新 更多