输入长度不定的一串数字(c++)
-
描述
在屏幕中,输入一行数字,以空格分隔。(数据长度未知)
例如:5 5 5 3 5 7 8 9
-
代码实现
vector<int> a;
while(scanf("%d",&x)!=EOF&&getchar()!='\n'){
a.push_back(x);
}
-
说明
- 网上还有其他博主的不同版本,但思路是相同的,不过在不同的环境下有些就是无法跳出循环(玄学问题),比如我所遇到的在同样的服务器上提交题目,同样的跳出条件,别人可以我却超时了,只能说这是一个玄学问题。
-
附上相关题目
-
数组主元素问题
所谓主元素就是在一个数组中的某一个元素所出现的的次数大于数组长度的1/2。存在则输出该元素,否则输出-1。
-
输入:5 5 5 3 5 7 5
-
输出:5
#include<iostream> #include<map> #include<vector> using namespace std; int main(){ char ch; int x; vector<int> a; map<int,int> mp; while(scanf("%d",&x)!=EOF&&getchar()!='\n'){ a.push_back(x); mp[x]++; } map<int,int>::iterator it=mp.begin(); int max=0,count=0; for(;it!=mp.end();it++){ if(it->second>max){ max=it->second; count=it->first; } } if(max>(a.size()/2)){ cout<<count; }else{ cout<<-1; } system("pause"); return 0; }
-