最近笔试的时候,编程题遇到这样要求的输入,需要输入一行整数,个数未知,然后整数之间用空格间隔,如下所示:
11 22 333 45 62
代码如下所示:
int main()
{
vector<int> inputs;
int n = 0, k=0;
int i;
cin >> i;
inputs.push_back(i);
while (cin.get() != '\n') {
cin >> i;
inputs.push_back(i);
}
system("pause");
return 0;
}
更完整代码如下所示,编程题目是要求找到给定整数序列中第K个大的数字:
#include<iostream>
#include<vector>
using namespace std;
int find_k_max_nums(vector<int> array, int k){
int res = 0;
sort(array.begin(), array.end(), greater<int>());
res = array[k - 1];
return res;
}
int main()
{
vector<int> inputs;
int n = 0, k=0;
int i;
cin >> i;
inputs.push_back(i);
while (cin.get() != '\n') {
cin >> i;
inputs.push_back(i);
}
cin >> k;
int res = find_k_max_nums(inputs, k);
printf("%d\n", res);
system("pause");
return 0;
}
结果如下: