【c++】在一组数中找出最小值的第二小的值

#pragma once
#include <iostream>
#include <vector>
#include "Test.h"
#include <stdlib.h>
#include<algorithm>

using std::cout;
using std::endl;

void fun(std::vector<double>& vecT,double& d1, double& d2)
{
	int nSize = (int)vecT.size();
	int nIdx1 = -1,nIdx2 = -1;
	d1 = 1e100;
	d2 = 1e100;
	for (int i = 0; i < nSize; i++)
	{
		if ( vecT[i] < d1 )
		{
			nIdx1 = i;
			d1 = vecT[i];
		}

		if ( vecT[i] < d2 && vecT[i] > d1 )
		{
			nIdx2 = i;
			d2 = vecT[i];
		}
	}
}

void main()
{
	std::vector<double> vecT;
	//srand(time(NULL));
	//int i=rand()%100; //产生0~SIZE-1的随机数
	for ( int i = 0; i < 100; i++)
	{
		vecT.push_back(rand());
	}
	double d1,d2;
	fun(vecT,d1,d2);
	cout <<"测试结果:" <<d1 <<"  " << d2 <<endl;

	sort(vecT.begin(),vecT.end());
	cout <<"准确结果:" <<vecT[0]<< "   " << vecT[1];
	system("pause");
}
测试结果:41  153
准确结果:41   153

请按任意键继续. . .


猜你喜欢

转载自blog.csdn.net/whueratsjtuer/article/details/52098013