数字在数组中重复的次数,C++
how many times the numbers repeat inside an array, C++
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;
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '