在c ++中计算重复数

Hmm*_*mmm 3 c++ duplicates

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

所以我想计算那些重复项并保存这些计数器以供日后使用.因为每个重复的数字应该用计数器除

像100重复2次,所以他们应该是50.

为了找到重复,我用了排序.

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

我试图使计数器数组将它们保存在每个数组上.但它不起作用.请给我一些更好的主意.

Chr*_*phe 6

方法1

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

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

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

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

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

方法2

如果您不允许使用地图,那么您必须详细说明计数循环,以便为每个新数字重新开始计数,并且如果超过两个,也能够处理连续的重复:

...
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;   
    }
}
Run Code Online (Sandbox Code Playgroud)

如果需要存储对以在第二步中处理它们,则需要存储一对(最好是在向量中,但如果在数组中需要):

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);  
    }
...
Run Code Online (Sandbox Code Playgroud)

这两种方法的在线演示