给出一系列已重复的数字和多少次数

时间:2013-06-08 13:31:45

标签: c++

例如

1 1 1 1 2 3 3 4 5 5 5

重复3次, 3次重复1次, 5次重复2次

这是代码,但它有一些麻烦

int i, k, m, number, number_prev, e;
cout << "Insert how many numbers: ";
cin >> m;
cout << "insert number";
cin >> number;
number_prev = number;
int num_rep[m]; //array of repeated numbers
int cant_rep[m]; // array of correspondent number of repetitions
e = 0;

for (i=1; i<m; i++) 
{
    cin >> number; 
    if (number == number_prev)
    {
        if (number == num_rep[e-1])
            cant_rep[e-1]++;
        else
        {
            num_rep[e] = number;
            cant_rep[e] = e + 1;
            e++;
        }
    }
    else
        e = 0;
    number_prev = number;
}

for (k = 0; k < e; k++)
    cout << "\nnumber " << num_rep[k] << " repeated " << cant_rep[k] << " times.\n";

3 个答案:

答案 0 :(得分:3)

您应该学习算法和数据结构。这使您的代码更简单。只使用保存对

的关联容器
a number --> how many times it repeats

可以充分简化您的计划

int main()
{
    std::map<int, int> map;
    int v;
    while(std::cin >> v) {
        map[v]++;
    }
    for (auto it = map.cbegin(); it != map.cend(); ++it) {
        if (it->second > 1) {
            std::cout << it->first << " repeats " << it->second - 1 << " times\n";
        }
    }
}

std::map是一个关联容器。

您可以将其视为具有唯一键的key-->value存储空间。

真实单词中的示例是字典:

您有 word 及其定义。单词是定义是一个值。

std::map<int,       int> map;
         ^^^        ^^^
          |           |
         key type    value type

您可以使用[]运算符引用值。

这与普通数组一样,除了 index 之外,您使用

您还可以使用 iterators 检查地图中的所有键值

it = map.cbegin(); // refers to the first key-value pair in the map
++it; // moves to the next key-value pair
it != map.cend(); // checks, if we at the end of map, so examined all elements already

我指出,地图保存了键值

在标准C ++库struct std::pair用于表达

它有firstsecond成员,代表第一和第二个值,并存储在一对中。

如果是地图,firstsecond

同样,我们将一个数字存储为一个键,在一个值中重复重复的次数。

然后,我们读取用户输入并为给定的增加

之后,我们只检查存储在地图中的所有元素并打印它们。

答案 1 :(得分:0)

int num_rep[m]; //array of repeated numbers
int cant_rep[m]; // array of correspondent number of repetitions

这里,m只在运行时才知道,数组大小必须在编译时知道。请改用std::vector

代码看起来像是C风格的C ++程序:

1.您不需要在块的开头声明变量。在使用之前声明它们,它更具可读性。

2.使用像STL这样的std::vector类型可以在这样的程序中省去很多麻烦。

答案 2 :(得分:0)

  1. 你说“插入m个数字”,但是for (i=1; i<m; i++)会循环m-1次,这可能不是你想要的。
  2. 作为补充建议,你应该对来自外部世界的变量进行输入检查。如cin >> m;,因为它可以是零或负数。