计算多个Array元素

时间:2017-11-02 14:41:28

标签: c++

我写了一个C ++程序,它向我展示了数组元素的重复次数...我的源代码是:

#include <iostream>
#include <string>
using namespace std;
int main() {
    int x[20] = {1,1,32,43,54,65,76,76,76,2,12,12,32,43,54,3,3,23,1,43};
    for (int i=0;i<20;i++) {
    }

    for (int i=0;i<20;i++) {
        int count=1;
        for (int j=i+1;j<19;j++) { 
            if (x[i]==x[j]) count++;
        }
        cout<<"The number "<<x[i]<<" is repeated "<<count<<" times"<<"\n";
    }
}

出来的是:

The number 1 is repeated 3 times
The number 1 is repeated 2 times
The number 32 is repeated 2 times
The number 43 is repeated 2 times
The number 54 is repeated 2 times
The number 65 is repeated 1 times
The number 76 is repeated 3 times
The number 76 is repeated 2 times
The number 76 is repeated 1 times
The number 2 is repeated 1 times
The number 12 is repeated 2 times
The number 12 is repeated 1 times
The number 32 is repeated 1 times
The number 43 is repeated 1 times
The number 54 is repeated 1 times
The number 3 is repeated 2 times
The number 3 is repeated 1 times
The number 23 is repeated 1 times
The number 1 is repeated 1 times
The number 43 is repeated 1 times

问题是输出每次都显示数组元素,但我希望我的程序只显示重复数组一次。我不想定义新的数组..任何人都知道发生了什么?

注意:没有定义任何新数组且没有排序程序输出应该是这样的:

    The number 1 is repeated 3 times
    The number 32 is repeated 2 times
    The number 43 is repeated 3 times
    The number 54 is repeated 2 times
    The number 65 is repeated 1 times
    The number 76 is repeated 3 times
    The number 2 is repeated 1 times
    The number 12 is repeated 2 times
    The number 3 is repeated 2 times
    The number 23 is repeated 1 times

3 个答案:

答案 0 :(得分:4)

您可以使用地图来计算元素,这可以满足您不创建新数组的要求。

std::map<int, int> counts;
for(auto&& elem : x)
{
    counts[elem]++;
}

for(auto&& item : counts)
{
    std::cout << "The number " << item.first << " is repeated " << item.second << " times; 
}

答案 1 :(得分:0)

如果没有额外的结构,您可以这样做:

#include <algorithm>
#include <iostream>
#include <string>

int main() {
    const int x[20] = {1,1,32,43,54,65,76,76,76,2,12,12,32,43,54,3,3,23,1,43};

    for (int i=0;i<20;i++) {
        if (std::find(x, x + i, x[i]) != x + i) {
            continue;
        }
        const auto count = std::count(x + i, x + 20, x[i]);
        std::cout << "The number " << x[i] << " is repeated " << count << " times\n";
    }
}

Demo

答案 2 :(得分:0)

这是 reduce 操作。 C ++在算法中有一个称为std::accumulate的左折操作。用std::map喂它来创建一个计数记录。

auto count_map = std::accumulate(std::begin(x), std::end(x),
                                 std::map<int, int>{},
                                 [] (auto& m, int val) -> decltype(m) {
    ++m[val];
    return m;
});

// Output result
for (auto&& [val, count] : count_map) {
    std::cout << "Value: " << val << " - Count: " << count << std::endl;
}
# Output:
Value: 1 - Count: 3
Value: 2 - Count: 1
Value: 3 - Count: 2
Value: 12 - Count: 2
Value: 23 - Count: 1
Value: 32 - Count: 2
Value: 43 - Count: 3
Value: 54 - Count: 2
Value: 65 - Count: 1
Value: 76 - Count: 3