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

how many times the numbers repeat inside an array, C++

本文关键字:C++ 数组 数字      更新时间:2023-10-16

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

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

该代码查找并打印数组中重复次数最多的数字以及自身重复的次数,我想把它改一下,这样它就会显示任何数字在数组中重复的次数。谢谢

只需添加一个类似的循环

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

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

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