在 C++ 中计算重复项

2022-01-10 00:00:00 duplicates 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

like 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.

推荐答案

方法一

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

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);  
    }
...

两种方法的在线演示

相关文章