vector
你可以使用and来做这样的事情sort()
:
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v;
srand((unsigned)time(0));
int random_integer;
int lowest=-10, highest=10;
int range=(highest-lowest)+1;
for(int index=0; index<20; index++){
random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0));
v.push_back(random_integer);
//cout << random_integer << ' ';
}
sort(v.begin(),v.end());
cout << endl << v[v.size()-2] << endl;
cout<<"\n=============== \n";
system("pause");
}
这只是打印第二高的数字:
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main()
{
srand((unsigned)time(0));
int random_integer;
int lowest=-10, highest=10;
int a=lowest,b=lowest;
int range=(highest-lowest)+1;
for(int index=0; index<20; index++){
random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0));
cout << random_integer << ' ';
if(a<random_integer)
{
a=random_integer;
continue;
}
if(b<random_integer)
{
b=random_integer;
continue;
}
//cout << random_integer << ' ';
}
cout << endl << min(a,b) << endl;
cout<<"\n=============== \n";
system("pause");
}