计算C ++中的重复项 [英] counting duplicates in c++

查看:123
本文介绍了计算C ++中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个整数数组{100,80,90,100,80,60}

Let's say I have an array of ints {100, 80, 90, 100, 80, 60}

所以我想计算这些重复项并保存这些计数器以备后用. 因为每个重复的数字都应按计数器除

so I want to count those duplicates and save those counter for later. because each duplicate number should be divided by counter

像100一样重复2次,因此每次应重复50次.

like 100 is duplicated 2 times so they should be 50 each.

要查找重复项,我使用了排序.

to find duplicates, I used sort.

std::sort(array, array + number);
for(int i = 0; i < number; i++) {
  if(array[i] == array[i+1])
    counter++;
}

,并且我尝试制作计数器数组以将其保存在每个数组中.但这没用.请给我一些更好的主意.

and I've tried to make counter array to save them on each num of array. but it didn't work. please give me some better idea.

推荐答案

方法1

最简单的方法是不对数组进行排序,而增加地图元素:

The easiest way, is not to sort your array, and increment elements of a map:

unordered_map<int, size_t> count;  // holds count of each encountered number 
for (int i=0; i<number; i++)        
    count[array[i]]++;             // magic ! 

然后您可以处理地图的内容:

You can then process the content of the map:

for (auto &e:count)                // display the result 
    cout << e.first <<" : "<<e.second<< "-> "<<e.first/e.second<<endl; 

如果需要,可以通过从地图中删除非重复项或在处理过程中忽略它们来过滤掉非重复项.

If needed, filter out the non duplicates by rerasing them from the map or ignoring it during the processing.

方法2

如果不允许使用地图,则必须详细说明计数循环,以便为每个新数字重新开始计数,并且如果两个以上都可以处理连续的重复项,则可以进行处理:

If you're not allowed to use maps, then you have to elaborate your counting loop, in order to restart counting for each new number, and being able to process consecutive dups also if more than two:

...
for(int i = 0; i < number; i+=counter) {
    for (counter=1; i+counter<number && array[i+counter]==array[i]; ) 
        counter++;       // count consecutives dups
    if (counter>1) {     // if more than one, process the dups.  
        cout << "dup: " << array[i] << " "<<counter<<endl;   
    }
}

如果您需要存储对以在第二步中进行处理,则需要存储对(最好在向量中,但如果需要在数组中):

If you need to store the pairs to process them in asecond step, you need to store a pair (preferably in a vector, but if needed in an array):

pair<int, size_t> result[number];  // a vector would be preferable
int nres=0; 
... 
    if (counter>1) {     // if more than one, process the dups.  
        // cout << "dup: " << array[i] << " "<<counter<<endl; 
        result[nres++] = make_pair(array[i], counter);  
    }
...

两种方法的在线演示

这篇关于计算C ++中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆