用重复的计数器分隔重复项

时间:2016-09-25 07:26:40

标签: c++

我尝试编写的程序从用户获取信息,检查重复重复并计算重复项。

例如,

{10,40,30,40,30}每个40和30重复2次

所以它应该是{10,20,15,20,15}

这是我的代码:

struct Data {
  int id;
  double weight
}
std::sort(p, p + num, acompare);
for (int i = 0; i < num; i += counter) {
    for (counter = 1; i + counter<num&& p[i + counter].weight== p[i].weight; )
        counter++;       // count consecutives dups

    if (counter>1) {     // if more than one, process the dups.  
            cntArr[i] = counter;
            cntArr[counter] = counter;
        } else 
            cntArr[i] = 1;  
}

for (int i = 0; i < num; i++) {
    cout << p[i].id << ":" << p[i].weight/ (double) cntArr[i] << endl;
}

,结果就像这样

输入:

1 100

2 100

3 100

4 80

5 80

输出:

4 40

5 -9.79969e-08

1 33.3333

2 33.3333

3 -1.18744e-07

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

调试代码中的特定问题有点困难,因为它不完整(无法将其复制粘贴到编辑器并构建它)。特别是,不确定pcntArray是什么,以及它们是如何初始化的。

然而,从根本上说,这段代码可以缩短和提高效率。而不是排序(立即Θ(n log(n))复杂度),使用std::unordered_map来存储每个元素的多重性。更短,更少的潜在错误和(预期)线性复杂性。

#include <vector>
#include <unordered_map>
#include <iostream>
#include <algorithm>

int main() {
    const std::vector<int> a{10, 40, 30, 40, 30};
    std::unordered_map<int, std::size_t> counts; 
    std::for_each(std::begin(a), std::end(a), [&](int e){ ++counts[e]; });
    std::for_each(std::begin(a), std::end(a), 
        [&](int e){ std::cout << e / static_cast<double>(counts[e]) << std::endl; });
}

输出:

$ ./a.out 
10
20
15
20
15