#include<bits/stdc++.h>
#include<cstring>
#define arraySize 10
using namespace std;
char returnMaxOccur(char *str);
int main()
{
char str[]="teet";
cout<<"The max occuring character is"<<" "<<returnMaxOccur(str)<<endl;
return 0;
}
char returnMaxOccur(char* str)
{
int high=-1;
char t;
int counter[arraySize]={0};
int len=strlen(str);
for(int i=0;i<len;i++)
{
counter[str[i]]++;
}
for(int i=0;i<len;i++)
{
if(high<counter[str[i]])
{
high=counter[str[i]];
t=str[i];
}
}
return t;
}
Run Code Online (Sandbox Code Playgroud)
在下面的问题#include<bits/stdc++.h>
包含时 ,输入字符串的结果如下,
1)teet: ans is t
2)eett: ans is e
3)ttee: ans is t
4)ette: ans is e
Run Code Online (Sandbox Code Playgroud)
但当我包括#include<iostream>
而不是#include<bits/stdc++.h>
结果是
1)teet: ans is e
2)eett: ans is t
3)ttee: ans is t
4)ette: ans is e
Run Code Online (Sandbox Code Playgroud)
这种行为的原因是什么,或者我做错了什么?
这是一个教科书案例,说明未定义的行为如何在看似奇怪的行为中表现出来.
实际上,包含不同的头文件可能会影响内存中某些位置的字节数,当你大大超出数组counter(大小为10)时,你会意外地观察到的字节,其索引可能会一直上升到255.
处理此任务的传统方法是使用a std::map<char, int>,它可以有效地用作"稀疏数组".如果做不到这一点,请确保在int[]每次可能的输入中都有足够的"插槽" .
(而且,海事组织,你不应该使用bits/stdc++.h 反正.)