数字在C ++中重复的次数

时间:2014-10-12 21:03:07

标签: c++ arrays map iterator numbers

我想知道如何检查我在数组中存储的数字重复次数! 那是我的代码:

const int max = 15;
int a[max] = { 1, 2, 3, 2, 1, 3, 2, 4, 1, 1, 0, 8, 7, 1, 2 }; //Input array
map<int, int> m;

for (int i = 0; i<max; i++)
{
    m[a[i]]++;  //Increment the value of key for counting occurances
}

int mostNumTimes =0;
int number = -999; //-999 represents invalid number
map<int, int>::iterator it = m.begin();
    for (; it != m.end(); it++)  //Find the number which occurred 
    {                           //most number of times
        if (it->second > mostNumTimes)
        {
            mostNumTimes = it->second;
            number = it->first;
        }
    }

if (number != -999)   //Print number and number of times it occurred
{
    cout << "Number: " << number << endl;
    cout << "Number of times occured: " << mostNumTimes << endl;
}
else
{
    cout << "Input array is empty" << endl;
}

此代码查找并打印最重复的数字以及在数组内重复多少次, 我要更改它,以便显示数组中任何数字重复的次数。谢谢!

2 个答案:

答案 0 :(得分:0)

std::map的迭代器指向键值。您可以使用第一个成员访问密钥,使用 second 来访问该值。这是您打印所有地图条目的方式:

map<int, int>::const_iterator it = m.begin();  // add const for safety
for ( ; it != m.end(); ++it)  //print all entries
{
    cout << "Number: " << (*it).first << endl;
    cout << "Number of times occured: " << (*it).second << endl;
}

您也可以使用auto:

for( const auto &entry : m) 
{
    cout << entry.first << '\t' << entry.second << endl;
}

答案 1 :(得分:0)

只需添加一个这样的循环

for ( const auto &p : m )
{
   std::cout << p.first << '\t' << p.second << std::endl;
}

或者你可以装饰它。:)

for ( const auto &p : m )
{
   std::cout << "Number " << p.first 
             << " occurs in the array " << p.second 
             << " times" << std::endl;
}