Description
定义MaxValue类,用于求一系列非零整数的最大值。其中:
数据成员elements用于存储所有输入的非零整数。
void append(int)用于向elements中添加一个新数据。
int getMax()用于求出elements中的最大值。
Input
输入若干个整数,以输入0表示输入结束。
Output
所有输入的非零整数中的最大值。
Sample Input
321
496
553
338
837
463
158
154
929
537
0
Sample Output
929
HINT
使用vector更为容易实现。
Append Code
append.cc,
int main()
{
int a;
MaxValue test;
cin>>a;
while (a != 0)
{
test.append(a);
cin>>a;
}
cout<<test.getMax()<<endl;
return 0;
}
AC代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class MaxValue
{
private:
vector<int> elements;
public:
void append(int i)
{
elements.push_back(i);//elements.insert(i);这样是不对的,因为没有位置,用insert的时候必须要加上位置;
}
int getMax()
{
vector<int>::iterator it;
sort(elements.begin(),elements.end(),greater<int>());
// return elements[0];//用这种方法输出最大的,和下面的方法都是对的;
it=elements.begin();
return *it;//不能少了上面的语句,直接return *it,因为没有给it指定位置即赋值;
}
};
int main()
{
int a;
MaxValue test;
cin>>a;
while (a != 0)
{
test.append(a);
cin>>a;
}
cout<<test.getMax()<<endl;
return 0;
}