简体   繁体   English

C++ 数组中的 integer 元素重复多少次

[英]how many times repeat integer elements in array in C++

#include <iostream>
using namespace std;

int main()
{
    setlocale(LC_ALL,"Turkish");

    int dizi[10]={9,30,3,6,9,20,3,6,10,9};
    int counter, j;
    for(int i=0; i<10; i++){
        counter=1;
        for(int j=i+1; j<10;  j++){
            if(dizi[i]==dizi[j+1]){
                counter++;
            }   
        }

        cout<<dizi[i]<<"\t:"<<counter<<endl;        
    }

}
   /*
   //THE RESULT
    9       :3   
    30      :1   
    3       :2   
    6       :2   
    9       :2   //WRONG I don't want this line to appear
    20      :1   
    3       :1   //WRONG I don't want this line to appear
    6       :1   //WRONG I don't want this line to appear
    10      :1   
    9       :1   //WRONG I don't want this line to appear
   */

I prefer to use the STL for such problems.对于此类问题,我更喜欢使用 STL。 Iterate over your array, count the occurence in counts and store the order in order .遍历您的数组,计算出现counts并按顺序存储order

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

int main() 
{
    int dizi[] = { 9, 30, 3, 6, 9, 20, 3, 6, 10, 9 };

    std::unordered_map<int, std::size_t> counts;
    std::vector<int> order;

    for (const auto &el : dizi) {
        if (counts.find(el) == counts.end()) order.push_back(el);
        ++counts[el];
    }

    for (const auto &el : order) {
        std::cout << el << "\t:" << counts[el] << '\n';
    }

    return 0;
}

Output: Output:

9   :3
30  :1
3   :2
6   :2
20  :1
10  :1

It seems you mean the following看来你的意思如下

#include <iostream>

int main() 
{
    int dizi[] = { 9, 30, 3, 6, 9, 20, 3, 6, 10, 9 };
    const size_t N = sizeof( dizi ) / sizeof( *dizi );

    for ( size_t i = 0; i < N; i++ )
    {
        size_t j = 0;

        while ( j != i && dizi[j] != dizi[i] ) ++j;

        if ( j == i )
        {
            size_t counter = 1;

            while ( ++j != N )
            {
                if ( dizi[j] == dizi[i] ) ++counter;
            }

            std::cout << dizi[i] << ":\t" << counter << '\n';
        }
    }

    return 0;
}

The program output is程序 output 是

9:  3
30: 1
3:  2
6:  2
20: 1
10: 1

That is you need to check whether a current value was already countered.那就是您需要检查当前值是否已经被抵消。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM