要求数组里的众数, 把数组先排序, 然后相邻的比较, map 分别存 数组值和 出现次数, 代码如下, 但没有输出结果。
#include "stdafx.h"
#include <iostream>
#include <map>
#include <string>
#include<algorithm>
using namespace std;
int main()
{
int a[] = { 1, 2, 3, 1, 4, 6,7 };
int count = 1;
int i;
map<int, int> map1;
sort(a, a + 7);
for (int i = 0; i < 7; i++)
{
if (i = 6) //越界
break;
if (a[i] == a[i + 1]);
count++;
map1[a[i]] = count;
// map1.insert(pair<int, int>(a[i], count));
count = 1;
}
map<int, int>::iterator it ;
for (it = map1.begin(); it != map1.end(); it++)
{
cout << it->first << " " << it->second << endl;
}
system("pause");
}
if (i = 6) //越界
break;
发现错误 , 这应该是
if (i == 6) //越界
break;
楼上说的很对
一个很早很老很实用的小笔记:楼主试着可以写 6 == i
以后也习惯这么写会有很多好处 一旦写错了 6 = i 就会报错 很好找
其实完全可以吧条件写成 小于6,,这样就不用判断==6 越界这个了,,,建议把count 初始值设为0,,,
你把那行注释去掉试试